【发布时间】:2013-04-29 22:34:53
【问题描述】:
我正在尝试实现一种选择排序算法,该算法将与链表一起使用,并将使用迭代器来遍历它们。选择排序算法如下:对于列表中除最后一个之外的每个元素(我们称之为K),它将从我们当前所在的位置开始寻找最小的on(因此它将从K开始直到最后一个元素)。之后它会swap K and the smallest element.
我认为我的错误在于第一个 for 循环;我很不确定--a.end() 是不是最后一个元素。我得到了一些输出,虽然它是错误的。
#include <iostream>
#include <list>
using namespace std;
void sort_list(list<int>& a)
{
//from the first until the pre-last element
for(list<int> :: iterator itr = a.begin(); itr != (--a.end()); ++itr)
{
int smallest = *itr;
//get smallest element after current index
list<int> :: iterator itr2 =itr;
++itr2;
for(; itr2 != a.end(); ++itr2)
{
if (smallest > *itr2)
{
smallest = *itr2;
}
}
//swap smallest and current index
int tmp = *itr;
*itr = smallest;
smallest = tmp;
}
}
int main()
{
//create a list and some elements
list<int> listi;
listi.push_back(5);
listi.push_back(4);
listi.push_back(3);
listi.push_back(2);
listi.push_back(1);
// sort the list
sort_list(listi);
//print all of the elements
for(list<int> :: iterator itr = listi.begin(); itr != listi.end(); ++itr)
{
cout << *itr << endl;
}
return 0;
}
【问题讨论】:
标签: c++ linked-list