I'm working on a homework assignment (we are allowed to get help), and I am 99% done, but I can't seem to get a simple array to sort from least to most. Its the last bug and I'm done with this thing.
The assignment is to do several things with an array that a user enters. I know my program is capturing the array just fine. However when I use the following functions to try to sort the entries from least to most I get weird outcomes. If the array is -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 it will sort the array fine but it will show 7 as the least number. Then I tried entering 4, 2, -1, 5, -4, 3, 8, and it sorted it into -1, -4, 3, 2, 4, 8, 5
-array is x
-len is length of array
Array gets passed to the selection function which is...
1 2 3 4 5 6 7 8 9
|
void selection(double x[], int len)
{
for(int i=len-1; i>=0; i--)
{
int j;
j=findmax(x,i);
swap(x[j],x[i]);
}
}
|
Explanation= Because array index values start at 0, and len is how many entries the array has, the len-1 is the top index number of the array. So the selection function will start with the full array, and the findmax function will find the biggest entry in the entry, and call the swap function to put that entry on top. So now the biggest element in the array is on top. Now the selection function passes findmax the array again only it ignores the top entry because we already know that was the largest, and the second largest entry is found and put into index len -2, and so on and so forth.
And then here are the findmax and swap functions...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
void swap(double& x, double& y)
{
double temp=x;
x=y;
y=temp;
}
int findmax(double x[], int len)
{
int current=0;
for (int i=1; i<len; i++)
{
if (x[i] > x[current])
{
current=i;
}
}
return current;
}
|
Thats it. Somewhere in that little bit of code something is going terribly wrong and I'm going cross eyed from looking at it so long.
I'm sure some experienced eyes will be able to set me straight pretty quick :) Thank you so much for any help in advance.