Insertion Sort | Pseudo Code of Insertion Sort | Insertion Sort in Data Structure
Insertion Sort is an efficient algorithm for sorting a small number of elements. It is similar to sort a hand of playing cards.
Playing a card is one of the techniques of sorting and in Insertion Sort we follow following steps.
– Start with an empty left hand and cards face down on the table.
– Then remove one card at a time from the table and Insert it into the correct position in the left hand.
– To find a correct position for a card, we compare it with each of the cards already in the hand from right to left.
In the same way, Insertion Sort works….The numbers that we wish to sort are known as Keys. Although conceptually we are sorting a sequence, then input comes to us in the form of an array with n elements.
Pseudocode of Insertion Sort
INSERTION-SORT(A)
1. for j = 2 to n
2. key ← A [j]
3. // Insert A[j] into the sorted sequence A[1..j-1]
4. j ← i – 1
5. while i > 0 and A[i] > key
6. A[i+1] ← A[i]
7. i ← i – 1
8. A[j+1] ← key
Let us take one example and see the Operations of Insertion Sort on the given Array. A= { 5 , 2, 4, 6, 1, 3}
I Hope you get the idea of how Insertion Sort Works 🙂