I am trying to create a sorting method based on selection sort algorithm With this current code, the array [10, 9, 8 .. 1] is "sorted" to [9, 8 .. 2, 10, 1] I mean like, it doesn't even put 10 in the right place
10 9 8 7 6 5 4 3 2 1
"sorted" to
9 8 7 6 5 4 3 2 10 1
What's the problem ?
void selectionSort(int array[], int length)
{
int i = 0, j = 0, temp = 0, swap = 0;
for(i = 0; i < length; i++)
{
temp = i;
for(j = 0; j < length; j++)
{
if(array[temp] > array[j])
{
temp = j;
}
}
swap = array[temp];
array[temp] = array[i];
array[i] = swap;
}
}
The inner loop should be written like
for(j = i + 1; j < length; j++)
^^^^^^^^^
After each iteration of i, the array upto i , should be sorted. You can print the array after each iteration of i and can see the logical error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.