Working of Insertion sort
Insertion sort is sorting mechanism which is best then both bubble sort and selection sort. The elements in the array are compared with the preceding elements.
In insertion sort array zeroth element is declared to be the sorted element, next element(first index) assume it as a key element, it is compared with its preceding elements one by one If any element in the preceding elements found to be greater than the key element then the key element will be shifted to the greater element index place and the greater element and its next elements move one step right(the index number of the greater element and its next elements will be increased by 1).
- here, in the example above 7 is declared to be sorted, so the comparison will start from the next element 6
- In step1, the 1st index element 6 is compared with the left side values in its array and takes its respective place after comparing the values of left side array elements
- In step2, the 2nd index element 5 is compared with its left side elements and will be inserted in its appropriate place
- Likewise, the iterations will be done until all elements in the array are sorted
The Time complexity of Insertion Sort
- Worst Case Time Complexity [ Big-O ]: O(n2)
- Best Case Time Complexity [Big-omega]: O(n)
- Space Complexity: O(1)