如何解决使用比较器进行选择排序
我非常非常困。我的代码运行并排序了一些东西,但我无法让它真正正确排序。我已经经历了很多次,我似乎无法弄清楚为什么它实际上不会按预期排序: 我的比较器应该返回 -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
);
}
}
}
}
}
}
任何帮助将不胜感激!
解决方法
我想出了答案,这是一个非常小的事情的经典案例.. 想了很久才弄明白。 if 和 second for 语句需要在交换之前关闭。就是这样。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。