[英]Bubble sort arraylist
我有一個從用戶讀入arraylist的對象數組,當我嘗試對基於String參數的數據進行冒泡排序時,程序遇到運行時錯誤,並且代碼未執行。
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;
}
}
}
您注意到那里有無限循環嗎? 以下while
循環:
while (finished = true)
...總是無限執行,因為由於該分配,表達式始終求值為true
。 這就是為什么您不應該比較布爾值的原因。 只需做:
while (finished) // this is enough.
這是我的解決方案:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.