PROWAREtech
C/C++: Selection Sort Algorithm
Another O(n²) algorithm.
This algorithm is useless because quick sort and insertion sort (among others) beat its pants off in every measure. While selection sort is not the quickest, it is not the slowest either, but it takes the same amount of time to sort a sorted array as to sort a random array. Bubble sort, on the otherhand, out performs them all on an already sorted array. Insertion sort has similar performance on sorted data. See the Algorithm Study for more details.
void selection_sort(int array[], const int size) {
int indexMin = 0, valueMin = 0;
const int bottom = (size - 1);
for(int top = 0; top < bottom; top++){
indexMin = top;
valueMin = array[top];
for(int seekMin = top + 1; seekMin < size; seekMin++)
if (array[seekMin] < valueMin){
valueMin = array[seekMin];
indexMin = seekMin;
}
array[indexMin] = array[top];
array[top] = valueMin;
}
}
Comment