Insertion Sort
Insertion Sort
6 10 24 36
12
INSERTION SORT
6 10 24 36
12
INSERTION SORT
6 10 24 3
6
12
INSERTION SORT
Before going through the program, lets see the steps of
insertion sort with the help of an example.
Input elements: 89 17 8 12 0
s
Step 3: 8 17 89 12 0
Step 4: 8 12 17 89 0
Step 5: 0 8 12 17 89
INSERTION SORT
Algorithm:--
for(i=1;i<n;i++)
{
k=a[i];
j=i-1;
while(j>=0 && a[i]>key)
{
a[j+1]=a[j];
j=j+1;
}
a[j+1]=key;
}
INSERTION SORT
#include<stdio.h>
int main()
{
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
// This loop would store the input numbers in array
for(i=0;i<conunt;i++)
scanf("%d",&number[i]);
// Implementation of insertion sort algorithm
for(i=1;i<count;i++)
{
temp=number[i];
j=i-1;
while((temp<number[j])&&(j>=0))
{
number[j+1]=number[j];
j=j-1;
}
number[j+1]=temp;
}
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}