1 Dec 2019

  • December 01, 2019
  • Amitraj
3. Selection Sort - 

-> Selection sort is a simple sorting algorithm which finds the smallest element in the array and exchanges it with the element in the first position. Then finds the second smallest element and exchanges it with the element in the second position and continues until the entire array is sorted.



In the above diagram, the smallest element is found in first pass that is 9 and it is placed at the first position. In second pass, smallest element is searched from the rest of the element excluding first element. Selection sort keeps doing this, until the array is sorted.



/* C program to implement Selection sort */

#include<stdio.h>
int main()
{
int a[50],i,j,n,pos,temp;
printf("Enter n value:");
scanf("%d",&n);
for(i=0;i<n;i++)
   scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
      if(a[pos]>a[j])
          pos=j;
     }
//if(pos!=i)
{
    temp=a[pos];
    a[pos]=a[i];
    a[i]=temp;
    }
     }
   printf("Sorted array is:");
   for(i=0;i<n;i++)
      printf("%d   ",a[i]);
return 0;
}


OUTPUT:

Enter n value:6
40 30 9 20 10 50
Sorted array is:9   10   20   30   40   50


Translate

Popular Posts