Sunday, 1 April 2012

Selection Sort


#include<stdio.h>
#include<conio.h>
#define max 20
void main()
{
 int n[max],i,j,k,m,temp,smallest;
 clrscr();
 printf("Enter the number of elements in the array:  ");
 scanf("%d",&m);
 for(i=0;i<m;i++)
 {
printf("Enter the element %d: ",i+1);
scanf("%d",&n[i]);
 }
 printf("Unsorted array is : \n");
 for(i=0;i<m;i++)
 printf(" %d ",n[i]);


 /* Selection sort  */
 printf("\n\n");
 for(i=0;i<m-1;i++)
 {
smallest=i;
for(k=i+1;k<m;k++)
{
if(n[smallest]>n[k])
smallest=k;
}
if(i!=smallest)
{
temp=n[i];
n[i]=n[smallest];
n[smallest]=temp;
}
printf("After pass %d elements are :  ",i+1);
for(j=0;j<m;j++)
printf(" %d ",n[j]);
printf("\n\n");
 }
printf("Sorted array is:  ");
for(i=0;i<m;i++)
printf(" %d ",n[i]);
printf("\n\n");
 getch();
}

No comments:

Post a Comment