Algorithms | Sorting | Question 5
Given an unsorted array. The array has this property that every element in the array is at most k distance from its position in a sorted array where k is a positive integer smaller than the size of an array. Which sorting algorithm can be easily modified for sorting this array and what is the obtainable time complexity?
Insertion Sort with time complexity O(kn)
Heap Sort with time complexity O(nLogk)
Quick Sort with time complexity O(kLogk)
Merge Sort with time complexity O(kLogk)
We can perform this in O(nlogK) time using heaps:
First, create a min-heap with first k+1 elements. Now, we are sure that the smallest element will be in this K+1 element. Now, remove the smallest element from the min-heap(which is the root) and put it in the result array. Next, insert another element from the unsorted array into the mean-heap, now, the second smallest element will be in this..extract it from the mean-heap and continue this until no more elements are in the unsorted array. Next, use a simple heap sort for the remaining elements.
O(k) to build the initial min-heap
O((n-k)logk) for remaining elements.
Thus we get O(nlogk). Hence, option B is correct.
Quiz of this Question
Please comment below if you find anything wrong in the above post