Insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there in each iteration. It repeats until no input elements remain. It always maintains a sorted sub list in the lower position of the list.
Time Complexity of this algorithm is O(n*n)
Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. Normally this algorithm is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced.
Binary search can reduce the number of comparisons in normal insertion sort. We can use Binary search due to find the proper location to insert the selected item of each iteration. At normal insertion, sort takes O(i) in worst case but it will take O(log i) by using binary search.
Algorithm
insertionSort(arr, n) // Sort an arr[] of size n
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
insertionSort(arr, n) // Sort an arr[] of size n
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
Bellow figure shows the insertion sort process. The shaded items will represent the order of each iteration.
Here bellow is another figure will show details process of a single iteration.