Saturday, 17 December 2011

Selection Sort

Here is the C implementation of Selection Sort for sorting 5 elements. You can replace 5 with the required size you wish to sort.


/*Selection Sort*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,j,index,smallest;
clrscr();
/*Get*/
printf("Enter the numbers to be sorted:\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
/*Sort*/
for(i=0;i<4;i++)
{
smallest=a[i];
index=i;
for(j=i+1;j<5;j++)
{
if(a[j]<smallest)
{
smallest=a[j];
index=j;
}
}
a[index]=a[i];
a[i]=smallest;
}
/*Print*/
printf("\nThe sorted numbers are:\n");
for(i=0;i<5;i++)
{
printf("%d\n",a[i]);
}
getch();
}

No comments:

Post a Comment