【发布时间】:2014-01-29 04:06:43
【问题描述】:
我正在编写一个气泡选择方法,它应该与这些凭据一起使用:
/* Write code for a Bubble Sort algorithm that starts at the right side of
* of ArrayList of Comparable objects and "bubbles" the largest item to the
* left of the list. The result should be an ArrayList arranged in descending
* order.
*/
@SuppressWarnings("unchecked")
void bubbleSort(ArrayList <Comparable> list) {
int end = list.size();
for (int i = 0 ; i < end; i++){
for (int j = end; j > 0; j--){
if ( list.get(j).compareTo(list.get(j-1)) > 0 ){
//swap
Comparable temp = list.get(j);
list.set(j,list.get(j - 1));
list.set(j - 1, temp);
//System.out.println(list);
}
}
end--;
}
}
问题是,Java 会告诉我它超出了范围。
如果我改为使用
for (int j = end - 1; j > 0; j--)
然后代码将运行,但它不会运行列表完全完成排序所需的运行次数(也就是它提前停止一个循环)
【问题讨论】:
-
在内部循环中,您有 N 个对象,并且您希望将每个对象与前一个对象进行比较以在需要时交换它们,因此您必须进行 N-1 个检查,因为第一个对象没有前一个对象.
for (int j = end - 1; j > 0; j--)是对的。
标签: java sorting arraylist indexoutofboundsexception