Selection Sort in C


Sorting means arranging a set of data in a particular order. It can be ascending or descending. Depending upon the size of the data to be sorted, sorting is mainly classified in two categories:

  1. Internal Sorting.
  2. External Sorting.

If all data can be stored inside the memory at the same time then we sort using internal sorting while when the data to be sorted is large in size and it need to be stored in external memory like hard disk then we use external sorting.

Selection Sort

It is an internal sorting method. In selection sort in 1st iteration we compare 1st element with all other elements so we get smallest element at first. Similarly, in second iteration we get 2nd smallest element at second position.

We require two for loop to sort an array using selection sort.

Select on element and compare it with all other

  for(i = 0; i<len-1; i++){
      for(j=i+1; j<len; j++){
         if(a[i]>a[j]){
         temp = a[i];
          a[i] = a[j];
          a[j] = temp;
         }
      }
  }

Complete code for selection sort

#include <stdio.h>
#include <string.h>

main()
{
  int a[7] = {54, 12, 23, 24, 5, 45, 99};
  int i = 0, j=0, temp;
  for(i = 0; i<6; i++){
      for(j=i+1; j<7; j++){
         if(a[i]>a[j]){
         temp = a[i];
          a[i] = a[j];
          a[j] = temp;
         }
      }
  }
  for(i=0;i<7;i++){
      printf("%d, ", a[i]);
  }
}

Screenshot: