It is a very simple method to sort the number in an increasing or decreasing order.
It has various advantages:
- It is simple to implement.
- It is efficient on small datasets.
- It is stable (does not change the relative order of elements with equal keys)
- It is in-place (only requires a constant amount O (1) of extra memory space).
- It is an online algorithm, in that it can sort a list as it receives it.
ALGORITHM: INSERTION SORT (A)
1. For k ← 2 to length [A]
2. Do key ← A[k]
3. i=k-1
4. while i>0 and A[i]>key
5. do A[i+1] ← A[i]
6. i=i-1
7. A[i+1] ← key
Analysis:
- Input: n elements are given.
- Output: the number of comparisons required to make sorting.
- Logic: If we have n elements in insertion sort, then n-1 passes are required to find a sorted array.
In pass 1: no comparison is required
In pass 2: 1 comparison is required
In pass 3: 2 comparisons are required
............................................................................
...............................................................................
In pass n: n-1 comparisons are required
Total comparisons: T (n) = 1+2+3+...........+ n-1
=
= o (n
2)
Therefore complexity is of order n2
Example:
Illustrate the operation of INSERTION SORT on the array A = (4, 15, 7, 18, and 16).
Solution:
A [] =
41571816
For j=2 to 5
- J=2, key=A [2]
- Key=15
- I=2-1=1, i=1
- While i>0 and A [1]>15
- A Condition false, so no change
- Now=3, key=A [3] =7
- I=3-1=2
- I=2, key=7
- While i>0 and A [2]>key
- Condition is true
- So A [2+1] ← A [2]
- A [3] ← A [2]
i.e.
4151816
- and i=2-1=1, i=1
- while i>0 and A [1]>key
- A Condition false. So no change
- Then A [1+1] ← key
- A [2] ← 7
That is
47151816
- For j=4
- Key=A [4]
- Key = 18, i=3
- Now, while 3>0 and A [3]>18
- The Condition is false, No change.
- Similarly, j=5
- Key=A [5]
- So key=16, i=4
- Now while 4>0 and A [4]>16
- Condition is true
- So A [5] =16 and i=4-1=3
- Now while 3>0 and A [3]>16
- Condition is false
- So A [3+1] =A [4] =16
And the sorted array is:
47151618