I am trying to implement a selection sort algorithm that will work with linked lists and will use iterators to scrool through them. The selection sort algorithm is the following: for each element of the list except the last one(let's call it K), it will seek out the smallest on from the position we are currently on(so it will start from K until the last element). After that it will swap K and the smallest element.
I think that my mistake is in the first for loop; I am very unsure that --a.end() is the pre-last element. I get some output, though it is wrong.
#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;
}