Sunday, 1 April 2012

Insertion Sort


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




/* Insertion Sort  */
for(j=1;j<n;j++)
{
k=a[j];
for(i=j-1;i>=0 && k<a[i];i--)
a[i+1]=a[i];
a[i+1]=k;
printf("Pass %d, Element inserted in proper place:  %d\n",j,k);
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
}
printf("Sorted list is : ");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
getch();
}

No comments:

Post a Comment