What is the worst case time complexity of insertion sort where positio...
Applying binary search to calculate the position of the data to be inserted doesn’t reduce the time complexity of insertion sort. This is because insertion of a data at an appropriate position involves two steps:
1. Calculate the position.
2. Shift the data from the position calculated in step #1 one step right to create a gap where the data will be inserted.
Using binary search reduces the time complexity in step #1 from O(N) to O(logN). But, the time complexity in step #2 still remains O(N). So, overall complexity remains O(N^2).
View all questions of this test
What is the worst case time complexity of insertion sort where positio...
Introduction:
Insertion Sort is a simple comparison-based sorting algorithm that builds the final sorted array one item at a time. The position of the data to be inserted can be calculated using binary search, which reduces the time complexity for finding the correct position to logarithmic time. However, the worst case time complexity of insertion sort still remains O(N^2) even with the optimization of binary search.
Explanation:
1. In insertion sort, the array is divided into two parts: sorted and unsorted.
2. Initially, the sorted part contains only the first element, and the unsorted part contains the remaining elements.
3. For each element in the unsorted part, it is compared with the elements in the sorted part to find the correct position for insertion.
4. Binary search can be used to find the correct position in the sorted part, reducing the number of comparisons required.
5. The worst case occurs when the array is in reverse order, i.e., the largest element is at the beginning.
6. In this case, for each element in the unsorted part, it needs to be compared with all the elements in the sorted part before finding the correct position.
7. The number of comparisons required for each element is 1, 2, 3, ..., N-1, which sums up to (N-1)*(N-2)/2.
8. Therefore, the total number of comparisons required in the worst case is (N-1)*(N-2)/2, which is a quadratic function of N.
9. Asymptotically, (N-1)*(N-2)/2 can be simplified to N^2, since the quadratic term dominates when N is large.
10. Hence, the worst case time complexity of insertion sort with binary search for finding the correct position is O(N^2).
Conclusion:
The worst case time complexity of insertion sort, even with the optimization of binary search for finding the correct position, is O(N^2). This occurs when the array is in reverse order, and for each element in the unsorted part, it needs to be compared with all the elements in the sorted part. Insertion sort is efficient for small input sizes or partially sorted arrays, but for large input sizes, other sorting algorithms like merge sort or quick sort with better time complexity should be considered.