Sorting Algorithm: Insertion Sort
Sorting Algorithm: Insertion Sort
Insertion Sort
Insertion Sort
In this technique we pick an element and
then insert it at the appropriate position in
ascending or descending order.
Insertion Sort
5 4 3 1 2
After insert 5 4 3 1 2
Find the appropriate position in the current range to insert the current element
Pass 1 of 4
Given array 5 4 3 1 2
5 4 3 1 2
Current Range
After insert 4 5 3 1 2
Find the appropriate position in the current range to insert the current element
Pass 2 of 4
From pass 1 4 5 3 1 2
4 5 3 1 2
Find the appropriate position in the current range to insert the current element
Pass 2 of 4
From pass 1 4 5 3 1 2
4 5 3 1 2
Current Range
After insert 3 4 5 1 2
Find the appropriate position in the current range to insert the current element
Pass 3 of 4
From pass 2 3 4 5 1 2
3 4 5 1 2
Find the appropriate position in the current range to insert the current element
Pass 3 of 4
From pass 2 3 4 5 1 2
3 4 5 1 2
Current Range
After insert 1 3 4 5 2
Find the appropriate position in the current range to insert the current element
Pass 4 of 4
From pass 3 1 3 4 5 2
1 3 4 5 2
Find the appropriate position in the current range to insert the current element
Pass 4 of 4
From pass 3 1 3 4 5 2
1 3 4 5 2
Current Range
After insert 1 2 3 4 5
Find the appropriate position in the current range to insert the current element
About Insertion Sort
• Insertion sort requires n-1 pass to sort an array of n
elements.
• In each pass we insert the current element at the
appropriate place so that the elements in the current
range is in order.
• In each pass we have k comparisons, where k is the
pass number.
• So, 1st pass requires 1 comparison.
• 𝑘 𝑡ℎ pass requires k-1 comparisons.
𝑡ℎ
• 𝑛 pass requires n-1 comparisons.
Algorithm
/*
a[0:n-1] is an array of n elements.
temp is a variable to facilitate exchange.
*/
InsertionSort(a,n)
Begin
for k = 1 to n-1 by 1 do //this is for pass
Set temp = a[k];
Set j = k-1;
while( temp < a[j] and j >= 0) do
Set a[j+1] = a[j];
Set j = j-1;
endwhile
Set a[j+1] = temp;
endfor
End
Order of Insertion Sort
For n elements array,
In 1st pass we have 1 comparison
In 2nd pass we have 2 comparisons
Similarly, in 𝑘 𝑡ℎ pass we have k comparisons
And the last pass requires 1 comparison
Therefore, total comparisons are
F(n) = 1+2+3+….+(n-3)+(n-2)+(n-1)
𝑛(𝑛−1)
= =0(𝑛2 )
2
Write a program in C to enter 5
elements and arrange them in
ascending order using Insertion sort
#include <stdio.h>
//function declaration
void insertionSort(int *a, int n);
int main(){
//variable declaration
int arr[5], i;
//input
for(i = 0; i < 5; i++)
scanf("%d", &arr[i]);
//sort
insertionSort(arr, 5); //passing arr address and no. of
elements
//output
for(i = 0; i < 5; i++)
printf("%d\n", arr[i]);
return 0;
}
//function definition
void insertionSort(int *a, int n){
int k, j, temp;
for(k = 1; k <= n-1; k++){
temp = a[k];
j = k-1;
while(temp < a[j] && j >= 0){
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
}
}