C Program to Sort Elements Using Selection Sort Algorithm
In this program you will learn that how to Sort Elements Using Selection Sort Algorithm
In this program you will learn that how to Sort Elements Using Selection Sort Algorithm
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.
#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;
}
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 . . .
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.