Insertion sort question

please explain insertion sort. thanks. it would be great if you could make a video on it.

Hello @siddhant

Insertion sort is similar to how you sort your cards in a game like rummy.
Let’s suppose you have 5 cards with numbers 4 2 3 1 5

So in insertion sort first you will sort the first two elements, then you will sort the first three elements, then you will sort the first four elements and so on…

In each iteration “i” you know elements before index “i” are all sorted because we sorted them, so now for element at index “i” we just need to place this one at its correct place before index “i” to sort the first “i” elements.

When you sort the first two elements, you sort compare the 2nd element with every element before it and place it at its correct place
(2 < 4) 2 4 3 1 5
END
When you sort the first three elements, you sort compare the 3rd element with every element before it and place it at its correct place
(3 < 4) 2 3 4 1 5
(3 > 2) STOP
When you sort the first four elements, you sort compare the 4th element with every element before it and place it at its correct place
(1 < 4) 2 3 1 4 5
(1 < 3) 2 1 3 4 5
(1 < 2) 1 2 3 4 5
END
When you sort the first five elements, you sort compare the 5th element with every element before it and place it at its correct place
(5 > 4) STOP

All sorted.

Let me know if you still need any help.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.