2012-02-17 79 views
0

我有一個快速簡單的問題,我無法找到答案。如何將對象數組的值傳遞給方法

我有一個名爲quick_srt_int的方法能夠對整數數組進行排序,但我的問題是,我的數組是從一個對象形成的,我希望能夠從一個特定的子值對數組進行排序(請糾正我關於如何調用)。

只是爲了給你一些背景,這是如何聲明數組。

student[index] = new Person(name, id, age, gpa); 

我需要能夠在不同時間對id,age和gpa進行排序,但不知道如何傳遞值。我的猜測是我必須這樣通過它:

public void ageSort() { 
    quick_srt_int(student[].age, 0, student[].age.length - 1); 
} 

請告訴我如何正確地做到這一點。

我還需要修改快速排序方法來支持double類型的值,因爲gpa是雙重形式的,我不能將它轉換爲排序。

任何幫助都非常感謝,非常感謝。

快速排序方法看起來像這樣:

public static void quick_srt_int(int array[], int low, int n) { 
    int lo = low; 
    int hi = n; 
    if (lo >= n) { 
     return; 
    } 
    int mid = array[(lo + hi)/2]; 
    while (lo < hi) { 
     while (lo < hi && array[lo] < mid) { 
      lo++; 
     } 
     while (lo < hi && array[hi] > mid) { 
      hi--; 
     } 
     if (lo < hi) { 
      int T = array[lo]; 
      array[lo] = array[hi]; 
      array[hi] = T; 
     } 
    } 
    if (hi < lo) { 
     int T = hi; 
     hi = lo; 
     lo = T; 
    } 
    quick_srt_int(array, low, lo); 
    quick_srt_int(array, lo == low ? lo + 1 : lo, n); 
} 

回答

0

作爲@Logan說,你必須使用比較器或你的Person類必須實現Comparable接口。我給你舉個例子:

public class Person implements Comparable { 
    private String name; 
    private int id; 
    private int age; 
    private int gpa; 

    public Person(String name, int id, int age, int gpa) { 
     this.name = name; 
     this.id = id; 
     this.age = age; 
     this.gpa = gpa; 
    } 
    //getters and setters here... 

    //logic for the comparison 
    //NOTE: you can improve the comparison algorithm. 
    public int compareTo (Person p) { 
     //0 means both Person objects are equal. 
     // > 0 means **this** object is greater than p object. 
     // < 0 means **this** object is less than p object. 
     int result = 0; 
     //comparison by id 
     if (this.id > p.id) { 
      result = 1; 
     } else { 
      if (this.id < p.id) { 
       result = -1; 
      } else { //same id, check by age 
       if (this.age > p.age) { 
        result = 1; 
       } else { 
        if (this.age < p.age) { 
         result = -1; 
        } else { //same id and age, check by gpa 
         if (this.gpa > p.gpa) { 
          result = 1; 
         } else { 
          if (this.gpa < p.gpa) { 
           result = -1; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
    return result; 
} 

而現在,人陣發送到您的快速排序方法:如果要指定此比較功能

public void ageSort() { 
    quick_srt_int(student[], 0, student[].age.length - 1); 
} 

public static void quick_srt_int(Person array[], int low, int n) { 
    //your logic... 
} 

,你需要添加一個參數傳遞到quick_srt_int函數來設置實現比較器接口的類。

+0

謝謝!我會嘗試的。 :) – 2012-02-18 04:30:01

0

你正在尋找一個Comparator。有一個與您的問題非常相似的示例here