2012-01-01 51 views
3

我有以下類。在這方面,虹膜是另一類有一些屬性的類。在Java中排序數組列表

public class Helper { 

    Iris iris; 
    double distance; 

    public Helper(Iris iris, double distance) { 
     this.iris = iris; 
     this.distance = distance; 
    } 
} 

我要排序的這樣的數組列表(即列表<助手> helperList),基於距離參數遞減。我寫了下面的方法,但它不起作用。

public void sort(){ 
for(int k=0; k < helperList.size(); k++) 
     { 
      double distance = helperList.get(k).distance; 

      for(int l=0; l < helperList.size(); l++) 
      { 
       Helper temp = helperList.get(l); 
       if(distance < temp.distance) 
       { 
        helperList.set(l, helperList.get(k)); 
        helperList.set(k, temp); 
       } 
      } 
     } 
} 

有人可以提出解決方案嗎?

+0

以何種方式是不工作? – 2012-01-01 07:49:40

+0

它沒有正確排序列表。 – Ammar 2012-01-01 07:53:13

+1

考慮兩個元素會發生什麼,比如'[1,2]'。對於'k = 0,l = 1',因爲'list.get(1)> 1',你交換,給出'[2,1]'。然後,對於'k = 1,l = 0',您再次交換。您應該將每個元素僅與其一側的元素進行比較。 – 2012-01-01 08:00:45

回答

17

爲什麼不讓Helper類實現Comparable接口,然後使用Collections類提供的內置排序方法。

Collections.sort(helperList) 

我認爲這樣可以解決問題。此外,這個sort方法是穩定的。

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

實現可比接口:

public class Helper implements Comparable{ 

    Iris iris; 
    double distance; 

    public Helper(Iris iris, double distance) { 
     this.iris = iris; 
     this.distance = distance; 
    } 

    public int compareTo(Helper other) { 
     return new Double(this.distance).compareTo(new Double(other.distance)); 

    } 
} 
+0

如果兩個距離相距小於1,則此compareTo實現將返回0(如果您要正確投射)。返回this.distance other.distance? 1:0; – jackrabbit 2012-01-01 08:14:31

+0

是的,謝謝長耳兔。我已經糾正了這個問題。 – Divya 2012-01-01 08:15:14

+0

它的工作原理。 感謝所有人,特別感謝@Divya對她的建議。 – Ammar 2012-01-01 08:33:43

0

bubble sort維基百科上的文章包含僞代碼,也有一些優化版本。與那個人比較一下,看看你哪裏出錯了。

冒泡排序是最明顯的排序算法之一,但不完全是最有效的。你爲什麼不讓平臺做這種事? java.util.Collections包含一個sort方法,可讓您提供自己的Comparator。比較所要做的就是決定兩個Helper實例中哪一個應該先到達。

1

的問題是,循環失去跟蹤的它已被調換後的距離指數的位置。這個算法應該很好。

for(int k = 1; k < helperList.size(); k++) { 
    double distance = helperList.get(k).distance; 
    int j = k - 1; 
    boolean done = false; 
    while(!done) { 
     Helper temp = helperList.get(j); 
     if(temp.distance < distance) { 
      helperList.set(j+1, temp); 
      j = j - 1; 
      if(j < 0) { 
       done = true; 
      } 
     } else { 
      done = true; 
     } 
     helperList.set(j+1, value); 
    } 
} 
+0

Thanx肖恩。我使用了Divya建議的Collections.sort(object),它工作正常。 – Ammar 2012-01-01 08:36:22

4

Divya's answer是好的,但如果你不想要實現Comparable接口,下面可能有幫助:

Collections.sort(helperList, new Comparator<Helper>() { 
    public int compare(Helper helper1, Helper helper2) { 
     return Double.compare(helper1.distance, helper2.distance); 
    } 
}) 
+1

'helper1.distance - helper2.distance'給出了double而不是int。我犯了同樣的錯誤。 – Divya 2012-01-01 08:19:48

+0

是的,你是對的:) – 2012-01-01 08:21:45