结构数组上的C++选择排序
C++ Selection Sort on Array of Structures
我正在读一本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类的成员属性中有任何指针,则可能具有意义。
您必须使用交换,而不仅仅是分配。
- C++选择排序算法中的逻辑错误
- 高级选择排序 - 在一次迭代中搜索两个元素
- 选择排序C++(已修改)并非适用于所有情况
- C++为什么我的指针选择排序中存在分段错误?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 修改的选择排序,选择最大的数字,然后交换到最后
- 如何选择排序一些结构
- 选择排序以查找未排序数组中的最大数字
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 给定数组范围的选择排序问题
- 选择排序算法生成无序结果
- 使用C 中的一系列字符串的选择排序
- 从递归向后选择排序函数调用 max 和交换函数
- 为 STL 列表编写选择排序
- 跟踪选择排序中的交换和比较次数
- 字母选择排序程序的问题