为 STL 列表编写选择排序

Writing a selection sort for STL list?

本文关键字:选择 排序 STL 列表      更新时间:2023-10-16

我正在编写一个特定的 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 参数,因为您没有使用它,而且实际上不需要它。