Saturday 6 December 2014

C Program for Insertion Sort Algorithm

Insertion Sort:

                  Insertion Sort is a Technique which inserts an element at an appropriate location by comparing each element with the corresponding elements at its left and moves the rest of the elements of the given array.

Program:

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[20],i,n,j,temp;
printf("\nEnter N Value:");
scanf("%d",&n);
printf("\nEnter Elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=n;i++)
{
j=i;
while(j>0&&a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
j--;
}
}
printf("\nSorted Elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
}

Output:

Enter N Value:5

Enter Elements:9
3
6
10
20

Sorted Elements are:
3
6
9
10
20











0 comments:

Post a Comment