【发布时间】:2021-09-04 01:24:49
【问题描述】:
我非常非常困难。我的代码运行并对某些内容进行排序,但我无法使其真正正确排序。我已经经历了很多次,我似乎无法弄清楚为什么它实际上不会按预期排序: 我的比较器应该返回 -1、0 或 1:
class SortByName implements Comparator<Student> {
public int compare(Student student, Student otherStudent) {
return student.getName().compareTo(otherStudent.getName());
}
}
class SortByRoll implements Comparator<Student> {
public int compare(Student student, Student otherStudent) {
if (student.getRollno() < otherStudent.getRollno()) {
return -1;
}
if (student.getRollno() == otherStudent.getRollno()) {
return 0;
}
else {
return 1;
}
}
}
我的选择排序我看不出有什么问题。
class SelectionSort {
public static void sort(
ArrayList<Student> studentList,
Comparator<Student> comparator
) {
for (int i = 0; i < studentList.size()-1; ++i) {
int currentMinIndex = i;
for (int j = i + 1; j < studentList.size(); ++j) {
if (
comparator.compare(
studentList.get(j),
studentList.get(currentMinIndex)
) < 0
) {
currentMinIndex = j;
if (currentMinIndex != i) { //If currentMinIndex isn't the last item to be sorted
//Swap!
Collections.swap(
studentList,
i,
currentMinIndex
);
}
}
}
}
}
}
任何帮助将不胜感激!
【问题讨论】:
-
由于我们立即交换,
currentMinIndex应始终为i。这使得变量currentMinIndex变得多余。作为回报,这使得内部if变得多余,我们应该交换索引i和j而不是i和currentMinIndex(Ideone demo)。 -
另一种(更常见的)方法是每次外循环迭代最多交换一次。我将把这个作为练习留给读者。
标签: java sorting arraylist sequence comparator