Insertion sort is next simple sorting algorithm after Bubble Sort. You may not have realized but you must have used insertion sort in lot of places in your life. One of the best example of insertion sort is,
how you sort your hand in playing cards. We pick one card from deck, we assume it's sorted, and then we insert subsequent card in their proper position. For example, if our first card is Jack, and our next card Queen then we put that after Jack. Now if next card is King, we put it after queen, and if we get 9, we put it before jack. So if you look closely, insertion sort is perfect sorting algorithm to insert new value in already sorted list. That's why best case complexity of insertion sort is
O(n), in which case you insert a new number in already sorted list of integers. Another thing to keep in mind is size of list, insertion sort is very good for small list or array, but not so for large list, where
QuickSort,
MergeSort and
HeapSort rules. Let's see one more example of insertion sort from real life. Have you noticed, how does tailors arrange shirts in wardrobe, according to size. So they insert new shirt at proper position, for that they shift existing shirts, until they find the proper place. If you consider wardrobe as array and shirts as element, you will find out that we need to shift existing elements to find right place for new element. This is the
core of insertion sort algorithm, if you understand these example, even you can come up with a step by step coding algorithm to sort an array of integer using insertion sort in Java. In this article, we will learn that by first understanding insertion sort with flowchart and by walking through an example. After than writing a Java method to do insertion sort will be very easy.