27/07/2011

Insertion Sort

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[50];
int i,j,key,n;
printf("Enter the no. of elements");
scanf("%d",&n);
printf("Now enter the elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

for(j=1;j<n;j++)
{
key=a[j];
i=j-1;
while(i>=0 &&a[i]>key)
{
a[i+1]=a[i];
i=i-1;
}
a[i+1]=key;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}

//*Note:Remember we are starting for loop from 1 because array indices start from 0

No comments:

Post a Comment