Reputation: 21
I'm trying to sort a list of numbers by passing a list of user-set length that's filled with random values to a function that will sort the elements in ascending order.
I've done this problem before using arrays and had no issue. For some reason my code isn't working, and I'd appreciate it if you guys could help me find out why it isn't working. It will sort the numbers but the last number will be unsorted.
Here is the function:
void sort(std::list<int>& numbers)
{
list<int>::iterator it;
list<int>::iterator it2;
for (it = numbers.begin(); it != numbers.end(); ++it)
{
for (it2 = ++numbers.begin(); it2 != numbers.end(); ++it2)
{
if (*it > *it2)
{
int temp = *it;
*it = *it2;
*it2 = temp;
}
}
}
}
Upvotes: 2
Views: 1661
Reputation: 2849
You algorithm didn't work, because second cycle always go through (almost) entire list again and again. What it should do, is only go through remaining portion. I.e. second cycle should be:
for (it2 = std::next(it1); it2 != numbers.end(); ++it2)
Also, since second cycle starts with "next" element, first cycle should go not until last element, but until second to last element. I.e. something like this:
for (it = numbers.begin(); it != std::prev(numbers.end()); ++it)
BUT, since std::prev()
is defined only for bidirectional iterators, and std::list
doesn't provide one, its probably easier rewrite it as:
for (it = numbers.begin(); std::next(it) != numbers.end(); ++it)
Upvotes: 3