结构数组上的C++选择排序

C++ Selection Sort on Array of Structures

本文关键字:选择 排序 C++ 数组 结构      更新时间:2023-10-16

我正在读一本C++书,其中一个难题让我有点不知所措。我正在学习指针,在这个特殊的问题上,我需要用一个学生名字的字符串和他们分数的两倍对一组结构进行排序(使用指针)。排序后,结构的数据成员显然仍然需要匹配(即,正确的名称仍然需要与其分数相匹配)。

这就是我的问题所在。到目前为止,我已经把分数按升序排列好了,但名字都乱了。我一直不知道为什么,部分原因是我仍在努力完全理解指针以及如何使用它们。我可以正确地进行冒泡排序,将名字与分数保持在一起,但不能进行选择排序。如果有任何帮助,我将不胜感激。

这是我对选择排序的功能:

void selection_sort(Student *ptr, int size) // selection sort - having some problems
{
  int start,
    min_index,
    min_value;
  for (start = 0; start < (size - 1); start++) {
    min_index = start;
    min_value = (ptr+start)->score;
    for (int index = start+1; index < size; index++) {
      if ( (ptr+index)->score < min_value) {
    min_value = (ptr+index)->score;
    min_index = index;
      }
    }
    // the following line is where, i think, the problem is, but i haven't
    // been able to figure out the solution, despite trying numerous approaches
    *(ptr+min_index) = *(ptr+start);
    (ptr+start)->score = min_value;
  }
}

所以这就是我所拥有的。我对排序算法也不太熟悉,这对我来说都是全新的,所以我希望它不会一团糟。如果在这些领域有知识的人能为我指明正确的方向,那就太棒了。

首先,我想给您一个提示:您可以使用ptr[min_index],而不是使用语法*(ptr+min_index),它将具有相同的效果。我相信这个版本更自然。

第二,你的问题。您应该交换ptr[min_index]ptr[start],而不是将其中一个的值复制到另一个。这不是:

*(ptr+min_index) = *(ptr+start);
(ptr+start)->score = min_value;

写下:

Student temp = ptr[start];
ptr[min_index] = ptr[start];
ptr[start] = temp;

或者,如果您正在使用c++,只需使用交换函数:

std::swap(ptr[min_index], ptr[start]);

为什么你应该交换而不是你目前正在做的事情?好吧,您应该保留ptr[min_index]中的所有字段,以便能够将它们分配给ptr[start]。

希望这能有所帮助。

我认为您应该在标准库中使用memcpy函数。。。

还有一件事:

*(ptr+min_index) = *(ptr+start); 

这一行似乎覆盖了数据,但没有按照应该的方式交换它们。

C++的第一课:在C++中,我们有运算符重载,因此行如下:

 *(ptr+min_index) = *(ptr+start); 

如果Student类的成员属性中有任何指针,则可能具有意义。

您必须使用交换,而不仅仅是分配。