I wrote this c++ function to sort an array, it works, but it doesn't seem to work with the fist value: it isalways the bigger instead of the smaller!
void s_iSort (double a[])
{
cout << "INCREASING SORTER:\n\n";
unsigned int mx,maxx;
double temp;
cout << "Insert maximum element to sort: "; cin>>mx;
for (int c=0; c<mx; c++)
{
maxx=0;
for (int i=c; i<mx; i++)
if (a[i]<a[maxx])
maxx=i;
temp=a[c];
a[c]=a[maxx];
a[maxx]=temp;
}
cout << "\nDONE!\n\n";
}
What's worng with this?
You should either use a debugger, or try to explain your algorithm to a rubber duck. However, I am in a rubber duck mood and will point you to a mistake:
for (int c=0; c<mx; c++) {
maxx=0;
for (int i=c; i<mx; i++) if (a[i]<a[maxx]) maxx=i;
temp=a[c];
a[c]=a[maxx];
a[maxx]=temp;
}
In each iteration of this loop you want to go trough a range of elements, find the minimum value in that range and put it as the first element of that range. It works for the first iteration, but already on the second it goes wrong. You initialize maxx
(which is supposed to be the first element in that range) to 0
, ie the first element of the array. However you should only consider elements that have not yet been sorted, ie change it to
maxx = c;
Also note, that (apart from exercises) you should not write your own sorting algorithm but use std::sort
.