Javatpoint Logo
Javatpoint Logo

Insertion Sort

It is a very simple method to sort the number in an increasing or decreasing order.

It has various advantages:

  1. It is simple to implement.
  2. It is efficient on small datasets.
  3. It is stable (does not change the relative order of elements with equal keys)
  4. It is in-place (only requires a constant amount O (1) of extra memory space).
  5. 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:

  1. Input: n elements are given.
  2. Output: the number of comparisons required to make sorting.
  3. 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
                          = DAA Insertion Sort
                          = o (n2)
    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 [] =

4 15 7 18 16

For j=2 to 5

i.e.

4 15 18 16

That is

4 7 15 18 16

And the sorted array is:

4 7 15 16 18





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA