• Design and Analysis of Algorithms
• Home

Design and Analysis Insertion Sort

Insertion sort is a very simple method to sort numbers in an ascending or descending order. This method follows the incremental method. It can be compared with the technique how cards are sorted at the time of playing a game.

The numbers, which are needed to be sorted, are known as keys. Here is the algorithm of the insertion sort method.

Algorithm: Insertion-Sort(A)
for j = 2 to A.length
key = A[j]
i = j – 1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key

Analysis

Run time of this algorithm is very much dependent on the given input.

If the given numbers are sorted, this algorithm runs in O(n) time. If the given numbers are in reverse order, the algorithm runs in O(n2) time.

Example

Unsorted list:

 2 13 5 18 14

1st iteration:

Key = a = 13

a = 2 < 13

Swap, no swap

 2 13 5 18 14

2nd iteration:

Key = a = 5

a = 13 > 5

Swap 5 and 13

 2 5 13 18 14

Next, a = 2 < 13

Swap, no swap

 2 5 13 18 14

3rd iteration:

Key = a = 18

a = 13 < 18,

a = 5 < 18,

a = 2 < 18

Swap, no swap

 2 5 13 18 14

4th iteration:

Key = a = 14

a = 18 > 14

Swap 18 and 14

 2 5 13 14 18

Next, a = 13 < 14,

a = 5 < 14,

a = 2 < 14

So, no swap

 2 5 13 14 18

Finally,

the sorted list is

 2 5 13 14 18

Useful Video Courses

Video

Compiler Design Online Training

102 Lectures 10 hours

Video

Sequential Circuit Design

30 Lectures 3 hours

Video

Design Patterns Online Training

31 Lectures 4 hours

Video

InDesign Online Training

43 Lectures 1.5 hours

Video

Canva: Become a Graphic Designer

7 Lectures 1 hours

Video

The Ultimate Canva Graphic Design Course

54 Lectures 4 hours