2013-09-23 90 views
0

我有一個從用戶讀入ArrayList中的對象數組,當我嘗試對基於String參數的數據進行冒泡排序時,程序遇到運行時錯誤並且代碼不執行。Bubble sort arraylist

Resort temp; 
    while (finished = true) { 
     finished = false; 
     for (int index = 0; index < numResorts - 1; index++) { 
      String nam1 = resorts.get(index).getName(); 
      String nam2 = resorts.get(index + 1).getName(); 
      if (nam1.compareTo(nam2) > 0) { 
       temp = resorts.get(index); 
       resorts.set(index, resorts.get(index + 1)); 
       resorts.set(index + 1, temp); 
       //resorts.get(index) = resorts.get(index + 1); 
       //resorts.get(index + 1) = temp; 
       finished = true; 
      } 
     } 
    } 

回答

4

你注意到你有一個無限循環呢?以下while循環:

while (finished = true) 

...總是無限的執行,因爲表達式始終評估爲true,因爲分配的。這就是你不應該比較布爾值的原因。簡單地做:

while (finished) // this is enough. 
+0

現在好了,我覺得完全白癡,謝謝。 – user2808723

0

這裏是我的解決方案:

List<Integer> sortedlists = new ArrayList<Integer>(); 
public List<Integer> sortBs(List<Integer> al) { 
    sortedlists = al; 
    for(Integer out = al.size()-1; out>1; out--) { 
     for(Integer i = 0; i < out;i ++){ 
      int n = i+1; 
      if(sortedlists.get(i) > sortedlists.get(n)) { 
       Integer temp = sortedlists.get(i); 
       sortedlists.set(i, sortedlists.get(n)); 
       sortedlists.set(n, temp); 
      } 
     } 
    } 

    return sortedlists; 
}