Sorting algorithm : selection sort in C

Selection sort is also one of the widely used sorting algorithm. In case of selection sort the smallest element is swapped with the first element. Then the second smallest element exchanges place with the second element and so on. We can also do this same process for the largest element. For that case the largest element well be swapped with the first element.

Here, we will implement this logic to sort a list of integers. Before going ahead see the process of sorting in case of selection sort algorithm. Here, the largest element will be swapped with the last element for sorting the array in ascending order.

selection-sort-algorithm-in-c-c-selection-sort

C program to sort elements using selection sort

// C program using selection sort algorithm

#include<stdio.h>

int main(){
  int num, c, d, t, number[50];

  printf("Enter the number of element here : ");
  scanf("%d", &num);

  printf("\nEnter %d integers to sort them : \n", num);

  for(c = 0; c < num; c++){
    scanf("%d", &number[c]);
  }

  for(c = 0; c < num; c++){

    for(d = c + 1; d < num; d++){

      if(number[c] > number[d]){
        t = number[c];
        number[c] = number[d];
        number[d] = t;
      }

    }
  }

  printf("\nAll the elements after sorting is : \n");
  for(c = 0; c < num; c++){
    printf("%d ",number[c]);
  }

  return 0;
}

Output of selection sort program

Enter the number of element here : 10

Enter 10 integers to sort them :
12 4 56 23 14 37 25 37 17 40

All the elements after sorting is :
4 12 14 17 23 25 37 37 40 56

Previous pageInsertion sort

Next pageQuicksort