I have this impementation of Selection sort algorithm. How to do this implementation as stable? I think its not possible/
int selection_sort1 ( int ai_numbers[], const int ci_count )
{
int counter = 0;
int i, minIndex, j;
for ( i = 0; i < ci_count; i++ )
{
minIndex = i;
for ( j = i + 1; j < ci_count; j++ )
{
if ( ai_numbers[j] < ai_numbers[minIndex] )
{
minIndex = j;
}
}
swap ( &ai_numbers[i], &ai_numbers[minIndex] );
counter++;
}
return counter;
}
Your implementation is not stable. At each iteration, you take the element at position
i
in the array and put it at an arbitrary position in the remaining array, so you mess up the original order.If you want a stable sort you have to:
i
without swapping. This means moving the remaining elements to the right to make space for thei
th element you are placing.This ensures elements with the same value are placed in the same order in the sorted array and in the original array.
(Thanks to Groo in comments for pointing out mistakes)