Python Searching and Sorting|Insertion sort

Insertion Sort Example-

Consider the following elements are to be sorted in ascending order-
6, 2, 11, 7, 5

The above insertion sort algorithm works as illustrated below-

Step-01: For i = 1

Step-02: For i = 2

Step-03: For i = 3

2

5

11

7

6

 

For j = 2; 11 > 7 so A[3] = 11

2

5

11

11

6

For j = 1; 5 < 7 so loop stops and A[2] = 7

2

5

7

11

6

After inner loop ends

Working of inner loop when i = 3

Step-04: For i = 4

Loop gets terminated as ‘i’ becomes 5. The state of array after the loops are finished-

With each loop cycle,

  • One element is placed at the correct location in the sorted sub-array until array A is completely sorted.

Visitor Counter

0051045