You are here

Selection sort in C

Selection sort in C: C program for selection sort to sort numbers. This code implements selection sort algorithm to arrange numbers of an array in ascending order. With a little modification, it will arrange numbers in descending order.

Selection sort algorithm implementation in C

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int array[100], n, c, d, position, swap;
  6.  
  7.   printf("Enter number of elements\n");
  8.   scanf("%d", &n);
  9.  
  10.   printf("Enter %d integers\n", n);
  11.  
  12.   for (c = 0; c < n; c++)
  13.     scanf("%d", &array[c]);
  14.  
  15.   for (c = 0; c < (n - 1); c++)
  16.   {
  17.     position = c;
  18.    
  19.     for (d = c + 1; d < n; d++)
  20.     {
  21.       if (array[position] > array[d])
  22.         position = d;
  23.     }
  24.     if (position != c)
  25.     {
  26.       swap = array[c];
  27.       array[c] = array[position];
  28.       array[position] = swap;
  29.     }
  30.   }
  31.  
  32.   printf("Sorted list in ascending order:\n");
  33.  
  34.   for (c = 0; c < n; c++)
  35.     printf("%d\n", array[c]);
  36.  
  37.   return 0;
  38. }

Output of program:
Selection sort C program output

Download Selection sort program.