如何使用选择排序按三个不同的方面进行排序

How to use selection sort to sort by three different aspects

我有一个学生class,由学生

组成
  1. 姓氏
  2. 名字
  3. 生日
  4. 编号
  5. 课程
  6. phone个数

我必须使用选择排序根据这三个属性对给定的学生列表进行排序:

  1. 生日
  2. 姓氏
  3. 名字

我什至不知道从哪里开始,因为所有在线示例都显示了如何对数字数组进行排序。这就是我现在的全部,肯定是不正确的。

        public void MinMax(StudentsRegister other)
    {
        
        StudentsRegister AllYearStudents = new StudentsRegister();
        for (int i = 0; i < AllYearStudents.StudentsCount() - 1; i++)
        {
            int smallest = i;
            for (int j = i + 1; j < AllYearStudents.StudentsCount(); j++)
            {
                if (AllYearStudents.Get(j) < other.Get(smallest))
                {
                    smallest = j;
                }
            }
        }
    }

OK,这明明是作业,我就不做了,不过不介意指点一下。您必须填写空白

您所拥有的代码似乎是合理选择排序算法的一部分,只是它没有交换代码。这是我从 tutorialspoint.com:

那里借来的算法
for (int i = 0; i < n - 1; i++) {
   smallest = i;
   for (int j = i + 1; j < n; j++) {
      if (arr[j] < arr[smallest]) {
         smallest = j;
      }
   }
   temp = arr[smallest];
   arr[smallest] = arr[i];
   arr[i] = temp;
}

数组是什么并不重要,只要 arr[j] < arr[smallest] 算出来就可以了。你只把它看作一个整数数组,但如果你有一个学生数组,你想知道的是“根据……,这个学生比那个学生低吗”。事情是,对于这个作业,你必须改变在“学生 X 小于学生 Y”选项中比较的字段

如果我们调用一个名为 IsLessThan 的方法,而不是 arr[j] < arr[smallest],那会怎样呢......它可能需要两个学生并比较他们的姓氏:

public bool IsLessThan(Student x, Student y){
  return x.LastName.CompareTo(y.LastName)<0;
}

记住,我们想要的只是一个布尔值决定“x 小于 y”——对于整数,即“2 小于 3”。姓氏是“琼斯比史密斯小”。

for (int i = 0; i < n - 1; i++) {
   smallest = i;
   for (int j = i + 1; j < n; j++) {
      if ( IsLessThan(arr[j], arr[smallest]) ) { //look, I've swapped out one bool test for another bool test
         smallest = j;
      }
   }
   temp = arr[smallest];
   arr[smallest] = arr[i];
   arr[i] = temp;
}

使用 just 一组学生(不是你喜欢的 StudentsRegister class),just 排序姓..

现在.. 当它起作用时,想一想“我们如何扩展它以使其按名字、姓氏或生日起作用?”。如果我们在某处有一些 IsLessThan 可以访问的变量,如果那个变量是一个东西,那么 lastname 将被划分,如果变量是另一个东西,那么 firstname 将被比较,如果变量是第三个东西那么出生日期将被比较。这意味着切换全部内置于 IsLessThan

完成后,也许您会喜欢尝试多态性方法,创建一个具有 IsLessThan 方法的 StudentComparer.. 然后是一个 StudentBirthdateComparer,该 StudentBirthdateComparer 扩展 StudentComparer 并覆盖 IsLessThan 并比较生日,另一个 StudentLastNameComparer 扩展 StudentComparer 并用姓氏比较覆盖 IsLessThan..

但要分阶段进行,否则你会感到困惑和迷失