Insertion Sort Algorithm
For Complete YouTube Video: Click Here
In this class, we will try to understand Insertion Sort Algorithm.
We have discussed the working mechanism of insertion sort in our previous classes.
Insertion Sort Algorithm
The algorithm for the insertion sort is shown below.
We will try to understand the insertion sort algorithm based on the array shown below.
The outer for loop of the insertion will iterate from j = 1 to n from j = 1 to 5.
The 0th element is not considered because there are no elements before it to compare.
The key element is the element in the jth index.
Now we will compare the key element with the elements to the left of it.
If the element to the left is greater than the key element, then the element in the ith position should be shifted to the “i + 1” th position.
The while loop will iterate till the end of the array, or one of the elements is smaller than the key element.
In every iteration of the for loop, one element is the key element, which will get shifted to its position in the sorted order.
For better understanding, click the YouTube link provided on the top.