Learn How Insertion Sort Method Works
Algorithm of Insertion Sort
| Step 1: | Repeat up to step 4 for I = 1 to N |
| Step 2: | KEY = a [I] |
| Step 3: | Repeat step 4 for J = I to 0 |
| Step 4: | If KEY < a [J - 1] then TEMP = a [J] a [J] = a [J - 1] a [J - 1] = TEMP |
Program of Insertion Sort
#include<stdio.h>
#include<conio.h>
#define N 5
void main()
{
void insertion(int *a);
int a[N],i;
clrscr();
printf("Enter Elements in array\n");
for(i=0;i<N;i++)
{
printf("Enter Value of A[%d]:",i);
scanf("%d",&a[i]);
}
insertion(a);
printf("Sorted List\n");
for(i=0;i<N;i++)
{
printf("A[%d]=%d\n",i,a[i]);
}
getch();
}
void insertion(int *a)
{
int i,j,temp,key,k;
for(i=1;i<N;i++)
{
key=a[i];
for(j=i;j>0;j--)
{
if(key<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
}