So post two of sorting algorithm refreshers. This time it's Selection Sort with the same crappy O(n^2) growth rate but with possibly less swaps.
- Start an outer loop from the start of the array counting till the end of the array
- Start an inner loop starting from the outer loops counter and going till the end of the array
- Using the inner loop keep track of the smallest/largest value
- After inner loop is complete swap the smallest value you found with the contents that is pointed to from the index of the outer loop
#include
int main(void) {
int list[] = { 3, 4, 1, 10, 23, 40, 2, 9};
int arr_length = sizeof(list)/sizeof(list[0]);
for(int i = 0; i < arr_length; ++i){
int min = i;
for( int j = i+1; j < arr_length; ++j) {
if( list[j] < list[min]) {
min = j;
}
}
if ( min != i) {
int temp = list[i];
list[i] = list[min];
list[min] = temp;
}
}
for( int i = 0; i < arr_length; ++i) {
printf("%d ", list[i]);
}
printf("\n");
}
No comments:
Post a Comment