为 STL 列表编写选择排序
Writing a selection sort for STL list?
我正在编写一个特定的 c++ 程序,以便在 STL 列表中使用选择排序,因为我的教授要求这样做。
我正在使用 Netbeans 9.2。目前,我被我的算法困住了。在最初的几次中,程序会编译,但选择后的列表总是以相同的值结束(假设它应该是 99、24、15、80、27,排序后它总是 1、1、1、1、1、2(。现在,直接的算法无法编译。我对编码相对较新。有人可以告诉我我做错了什么以及我应该怎么做吗?非常感谢!
这是我的代码:
void selectionSort(list<short> l, int size) {
list<short>::iterator it1;
list<short>::iterator it2;
list<short>::iterator it3;
short min, temp;
for(it1 = l.begin(); it1 != l.end(); it1++) {
temp = min = *it1;
it2 = it1;
for(it2 = it1; it2 != l.end(); it2++) {
if(*it2 < min) {
min = *it2;
it3 = it2;
}
}
*it1 = min;
*it3 = temp;
//Increment the first counter at the end
temp = min = *it1;
}
}
您的代码中存在一个错误,会导致崩溃。我已经在下面的代码中修复了它。
但我仍然不知道为什么它会输出奇怪的数字,如 1、1、1、1、2。也许这是由其余代码引起的。如果可以提供更多的代码或信息,将会很有帮助。
void selectionSort(list<short> l, int size) {
list<short>::iterator it1;
list<short>::iterator it2;
list<short>::iterator it3;
short min, temp;
for(it1 = l.begin(); it1 != l.end(); it1++) {
temp = min = *it1;
it2 = it1;
it3 = l.end(); // NOTE: to fix the bug
for(it2 = it1; it2 != l.end(); it2++) {
if(*it2 < min) {
min = *it2;
it3 = it2;
}
}
if (it3 != l.end()) { // NOTE: to fix the bug
*it1 = min;
*it3 = temp;
} // NOTE: to fix the bug
//Increment the first counter at the end
temp = min = *it1; // NOTE: This is unnecessary
}
}
您按值传递参数l
,而不是按引用传递。这就是为什么您在函数selectionSort
中执行的操作不会更改列表的原因。这是一个有效的版本:
#include <iostream>
#include <list>
void selectionSort(std::list<short>& l) {
std::list<short>::iterator it1;
std::list<short>::iterator it2;
std::list<short>::iterator it3;
short min, temp;
for(it1 = l.begin(); it1 != l.end(); it1++) {
temp = min = *it1;
it3 = l.end();
for(it2 = it1; it2 != l.end(); it2++) {
if(*it2 < min) {
min = *it2;
it3 = it2;
}
}
if (it3 != l.end()) {
*it1 = min;
*it3 = temp;
}
}
}
int main()
{
std::list<short> mylist= {10,1,8,13,14,7,6,5,18,9,19,12,17,15,4,2};
selectionSort(mylist);
std::list<short>::iterator it;
std::cout << "elements in listn";
for (it = mylist.begin(); it != mylist.end(); it++) {
std::cout << *it << std::endl;
}
return 0;
}
简而言之,您需要在selectionSort
函数声明中的l
类型之后添加一个&
。
更新
我从代码中删除了 size
参数,因为您没有使用它,而且实际上不需要它。
相关文章:
- C++选择排序算法中的逻辑错误
- 高级选择排序 - 在一次迭代中搜索两个元素
- 选择排序C++(已修改)并非适用于所有情况
- C++为什么我的指针选择排序中存在分段错误?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 修改的选择排序,选择最大的数字,然后交换到最后
- 如何选择排序一些结构
- 选择排序以查找未排序数组中的最大数字
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 给定数组范围的选择排序问题
- 选择排序算法生成无序结果
- 使用C 中的一系列字符串的选择排序
- 从递归向后选择排序函数调用 max 和交换函数
- 为 STL 列表编写选择排序
- 跟踪选择排序中的交换和比较次数
- 字母选择排序程序的问题