Write a program to explain selection sort. Which type of technique does it belong?

In selection sort, the list is divided into two sub-lists sorted and unsorted. These two lists are divided by an imaginary wall. We find the smallest element from unsorted sub-list and swap it to the beginning. And the wall moves one element ahead, as the sorted list is increases and the unsorted list is decreased.
Assume that we have a list of n elements. By applying selection sort, the first element is compared with all remaining (n-1) elements. The smallest element is placed at the first location. Again, the second element is compared with remaining (n-1) elements. At the time of comparison, the smaller element is swapped with the larger element. Similarly, the entire array is checked for smallest element and then swapping is done accordingly. Here we need n-1 passes or iterations to completely rearrange the data.



Implementation of selection sort in C language:
#include<stdio.h>
int main( )
{
int i,j,t,n,min,a[10];
printf("How many elements you want to sort? \n");
scanf("%d",&n);
printf("\n Enter elements for an array: \n");
for(i=0;i<n;i++)
{
printf("a[%d] = ",i);
scanf("%d",&a[i]);
printf("\n");
}
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
if(a[j] > a[min])
{
min=j;
}
t=a[i];
a[i]=a[min];
a[min]=t;
printf("\nAfter sorting the elements are: \n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

The program output is tested on www.jdoodle.com
Output:
How many elements you want to sort? 
6
Enter elements for an array: 
a[0] = 2
a[1] = 4
a[2] = 6
a[3] = 8
a[4] = 7
a[5] = 5



After sorting the elements are: 
8 7 6 5 4 2 


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: