Reputation: 1
Please have a look at this code. It's supposed to sort it in non-decreasing order, but for some reason it puts the largest element first then the rest in the correct order.
int min(int start)
{
int minimum = list[start];
int location = 0;
for (int i = start; i < size; i++)
{
if (list[i] < minimum)
{
minimum = list[i];
location = i;
}
}
return location;
}
void sort()
{
int minimum;
for (int i = 0; i < size; i++)
{
minimum = min(i);
int temp = list[i];
list[i] = list[minimum];
list[minimum] = temp;
}
}
Upvotes: 0
Views: 65
Reputation: 596352
@Slava explained why your existing code is broken and how to fix it.
I'd like to offer an alternative solution - learn to use standard STL algorithms.
Such as the std::sort()
algorithm:
Sorts the elements in the range [first, last) in ascending order
#include <algorithm>
void sort()
{
std::sort(&list[0], &list[size]);
}
Even if you want to implement your own sort()
logic (though std::sort()
does allow you to pass in a custom functor to implement custom sorting), your min()
function could use the STL std::min_element()
algorithm, and your sort()
function could use the STL std::swap()
algorithm:
#include <algorithm>
int min(int start)
{
int *found = std::min_element(&list[start], &list[size]);
return std::distance(&list[0], found);
}
void sort()
{
for (int i = 0; i < size; i++)
{
int minimum = min(i);
if (minimum != i)
std::swap(list[i], list[minimum]);
}
}
Upvotes: 1
Reputation: 44258
int location = 0;
you initialize location to 0 and if list[start]
is already minimum and start
!= 0 you return incorrect location. change it to
int location = start;
or you can use start
instead of location
:
int min(int start)
{
for (int i = start + 1; i < size; i++)
{
if (list[i] < list[start])
start = i;
}
return start;
}
Upvotes: 0