【发布时间】:2015-12-03 13:19:39
【问题描述】:
所以这是一个有点愚蠢的问题,但我在类上的 selectionSort 方法有问题。它每次都交换 ArrayList 数据,而不是仅在一项较小时交换。我知道这是一个括号问题,但我不知道在哪里删除/添加括号。
// Sort using selectionSort and call compareTo methods to evaluate
public static ArrayList selectionSort(ArrayList<Person> array) {
int smallestIndex;
Person smallestValue;
for (int index = 1; index < array.size(); index++) {
smallestValue = array.get(index);
smallestIndex = index;
for (int i = index + 1; i < array.size(); i++) {
if (smallestValue.compareTo(array.get(i)) == 1)
{
// update smallest
smallestValue = array.get(i);
smallestIndex = i;
}
// do nothing if the curIndex has the smallest value
else if (smallestIndex == index)
;
// swap values otherwise else
else {
Person temp = array.get(index);
array.set(index, array.get(smallestIndex));
array.set(smallestIndex, temp);
}
}
}
return array;
}
【问题讨论】:
-
index不应该从 0 开始?请发布Person对象 -
嗨实际上
compareTo()为String工作但我可以在这里看到你实际上正在使用一个对象Person该类是否覆盖compareTo方法?然后请发布PersonClass 你是如何覆盖的,因为你说每次迭代它的交换元素你的覆盖逻辑可能是错误的, -
您应该了解
compareTo()的工作原理:docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
标签: java sorting arraylist selection-sort