C Program to Sort Elements Using Selection Sort Algorithm

Data Structure / Sorting

1124

Selection sort algorithm starts by comparing first two elements of an array and swapping if necessary, i.e., if you want to sort the elements of array in ascending order and if the first element is greater than second then, you need to swap the elements but, if the first element is smaller than second, leave the elements as it is. Then, again first element and third element are compared and swapped if necessary. This process goes on until first and the last element of an array is compared. This completes the first step of selection sort.

If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get the required result. But, for better performance, in second step, comparison starts from second element because after first step, the required number is automatically placed at the first (i.e, In case of sorting in ascending order, smallest element will be at first and in case of sorting in descending order, the largest element will be at first.). Similarly, in the third step, comparison starts from the third element and so on.

A figure is worth 1000 words. This figure below clearly explains the working of selection sort algorithm.

Program:

#include <stdio.h>
int main()
 {
    int data[100],i,n,steps,temp;
    printf("Enter the number of elements to be sorted: ");
    scanf("%d",&n);
    for(i=0;i<n;++i)
      {
       printf("%d. Enter element: ",i+1);
       scanf("%d",&data[i]);
    }
    for(steps=0;steps<n;++steps)
    for(i=steps+1;i<n;++i)
     {
         if(data[steps]>data[i])  
/* To sort in descending order, change > to <. */
          {
             temp=data[steps];
             data[steps]=data[i]; 
             data[i]=temp;
         }
    }
    printf("In ascending order: ");
    for(i=0;i<n;++i)
        printf("%d  ",data[i]);
    return 0;
}

Output:

Enter the number of elements to be sorted: 6
1. Enter element: 9
2. Enter element: 7
3. Enter element: 6
4. Enter element: 54
5. Enter element: 3
6. Enter element: 2
In ascending order: 2  3  6  7  9  54  Press any key to continue . . .

Explanation:

Note: Though this program is in C, selection sort algorithm can be similarly used in other programming languages as well.

Selection sort algorithm is easy to use but, there are other sorting algorithm which perform better than selection sort. Specially, selection sort shouldn't be used to sort large number of elements if the performance matters in that program.

This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.