Home Programs Selection Sort Program in C Language

Selection Sort Program in C Language

0
12

Sorting Program in C Language – In Selection sort, the smallest element is exchanged with the first element of the unsorted list of elements (the exchanged element takes the place where smallest element is initially placed). Then the second smallest element is exchanged with the second element of the unsorted list of elements and so on until all the elements are sorted. In the following C program we have implemented the same logic.

<img width=

Before going through the program, lets see the steps of selection sort with the help of an example:
Entered elements: 22 0 -90 89 17

  • Step 1: -90 0 22 89 17 (22 and -90 exchanged position)
  • Step 2: -90 0 22 89 17 (0 is at right place, no exchange needed)
  • Step 3: -90 0 17 89 22 (22 and 17 exchanged position)
  • Step 4: -90 0 17 22 89 (89 and 22 exchanged position)

C Program – Selection sort

#include<stdio.h>
int main(){
   /* Here i & j for loop counters, temp for swapping,
    * count for total number of elements, number[] to
    * store the input numbers in array. You can increase
    * or decrease the size of number array as per requirement
    */
   int i, j, count, temp, number[25];

   printf("How many numbers u are going to enter?: ");
   scanf("%d",&count);

   printf("Enter %d elements: ", count);
   // Loop to get the elements stored in array
   for(i=0;i<count;i++)
      scanf("%d",&number[i]);
 
   // Logic of selection sort algorithm
   for(i=0;i<count;i++){
      for(j=i+1;j<count;j++){
         if(number[i]>number[j]){
            temp=number[i];
            number[i]=number[j];
            number[j]=temp;
         }
      }
   }

   printf("Sorted elements: ");
   for(i=0;i<count;i++)
      printf(" %d",number[i]);

   return 0;
}

Output:

As you can see that we have entered 6 elements in random order and the program sorted them in ascending order by using selection sort algorithm which we have implemented in the program. You can also modify this same program to sort the elements in descending order as well.

Cheers!

ShareTweetShare

READ MORE

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here