Home  • Programming • C

Selection sort algorithm in C

Selection sort The idea of Selection Sort is rather simple. It basically determines the minimum (or maximum) of the list and swaps it with the element at the index where its supposed to be. The process is repeated such that the nth minimum (or maximum) element is swapped with the element at the n-1th index of the list. The below is an implementation of the algorithm in C.
void SelectionSort(int a[], int array_size)
{
     int i;
     for (i = 0; i < array_size - 1; ++i)
     {
          int j, min, temp;
          min = i;
          for (j = i+1; j < array_size; ++j)
          {
               if (a[j] < a[min])
                    min = j;
          }

          temp = a[i];
          a[i] = a[min];
          a[min] = temp;
     }
}
Consider the following table. (Note that each pass represents the status of the array after the completion of the inner for loop, except for pass 0, which represents the array as it was passed to the function for sorting)
8 6 10 3 1 2 5 4 } pass 0 1 6 10 3 8 2 5 4 } pass 1 1 2 10 3 8 6 5 4 } pass 2 1 2 3 10 8 6 5 4 } pass 3 1 2 3 4 8 6 5 10 } pass 4 1 2 3 4 5 6 8 10 } pass 5 1 2 3 4 5 6 8 10 } pass 6 1 2 3 4 5 6 8 10 } pass 7
At pass 0, the list is unordered. Following that is pass 1, in which the minimum element 1 is selected and swapped with the element 8, at the lowest index 0. In pass 2, however, only the sublist is considered, excluding the element 1. So element 2, is swapped with element 6, in the 2nd lowest index position. This process continues till the sub list is narrowed down to just one element at the highest index (which is its right position).

Comments 0


Share

Copyright © 2024. Powered by Intellect Software Ltd