5/01/2009

C Program Insertion Sort


/*C Program Insertion Sort*/
#include<stdio.h>
#include<conio.h>
void main()
{
    int a[20],n,temp,i,j;

    printf("Enter the no of elements:\n");
    scanf("%d",&n);
    printf("Enter %d elements:\n",n);
    for(i=0; i<n; i++)
        scanf("%d",&a[i]);
    for(i=1; i<n; i++)
    {
        temp=a[i];
        j=i-1;
        while(temp<a[j]&&j>=0)
        {
            a[j+1]=a[j];
            j=j-1;
        }
        a[j+1]=temp;
    }
    printf("Sorted elements are:\n");
    for(i=0; i<n; i++)
        printf(" %d \n",a[i]);

}
Out Put:
Enter the no of elements:
8
Enter 8 elements:
21
23
48
95
64
51
79
321
Sorted elements are:
 21
 23
 48
 51
 64
 79
 95
 321

No comments:

Post a Comment