In this tutorial you will learn about the Selection Sort Algorithm and its application with practical example.
Selection sort algorithm is a simple sorting algorithm which sort a given set of n
number of unsorted elements. In selection sort, smallest element from an unsorted list is selected in every pass and placed at the beginning of the unsorted list.
Working of Selection Sort
The selection sort algorithm first find the smallest element in the array and swap it with the element at first position. Then, find the second smallest element in the array and swap it with the element at second position. This process is repeated until we get the sorted array.
Selection Sort Program In C
In the following C program we have implemented the Selection Sort Algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include<stdio.h> int main(){ int i, j, n, temp, nums[30]; printf("Enter number of elements: "); scanf("%d",&n); printf("Enter %d integer elements\n", n); // Loop to input the elements for(i=0;i<n;i++) scanf("%d",&nums[i]); // Implementation of selection sort algorithm for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(nums[i]>nums[j]){ temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } } printf("Elements after sorting: "); for(i=0;i<n;i++) printf(" %d",nums[i]); return 0; } |
Output:-