【问题标题】:Selection Sort with Comparators带比较器的选择排序
【发布时间】: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


【解决方案1】:

我找到了答案,这是一个如此小事的经典案例。我认为这需要很长时间才能弄清楚。 if 和 second for 语句需要在交换之前关闭。就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多