Introduction: This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.
Step 1:We take an unsorted array for our example.
Step 2:Insertion sort compares the first two elements.
Step 3:It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
Step 4:Insertion sort moves ahead and compares 33 with 27.
Step 5:And finds that 33 is not in the correct position.
Step 6:It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-list remains sorted after swapping.
Step 7:By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
Step 8:These values are not in a sorted order.
Step 9:So we swap them.
Step 10:However, swapping makes 27 and 10 unsorted.
Step 11:Hence, we swap them too.
Step 12:Again we find 14 and 10 in an unsorted order
Step 13:We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items. This process goes on until all the unsorted values are covered in a sorted sub-list.