Selection Sort in Data Structure

Selection Sort

  • Selection sort is a simple sorting algorithm which finds the smallest element in the array and exchanges it with the element in the first position. Then finds the second smallest element and exchanges it with the element in the second position and continues until the entire array is sorted.

  • selection sort

  • In the above diagram, the smallest element is found in first pass that is 9 and it is placed at the first position. In second pass, smallest element is searched from the rest of the element excluding first element. Selection sort keeps doing this, until the array is sorted.

Example: Program for Selection Sort

#include <stdio.h>

int main()
{
   int array[100], n, c, d, position, swap;
   printf("Enter number of elements\n");
   scanf("%d", &n);
   printf("Enter %d integers\n", n);
   for ( c = 0 ; c < n ; c++ )
      scanf("%d", &array[c]);
   for ( c = 0 ; c < ( n - 1 ) ; c++ )
   {
      position = c;
      for ( d = c + 1 ; d < n ; d++ )
      {
         if ( array[position] > array[d] )
            position = d;
      }
      if ( position != c )
      {
         swap = array[c];
         array[c] = array[position];
         array[position] = swap;
      }
   }
   printf("Sorted list in ascending order:\n");
   for ( c = 0 ; c < n ; c++ )
      printf("%d\n", array[c]);
   return 0;
}


Output:

selection sort output