Given an unsorted array. The array has this property that every element in array is at most k distance from its position in sorted array where k is a positive integer smaller than size of array. Which sorting algorithm can be easily modified for sorting this array and what is the obtainable time complexity?
(A) Insertion Sort with time complexity O(kn)
(B) Heap Sort with time complexity O(nLogk)
(C) Quick Sort with time complexity O(kLogk)
(D) Merge Sort with time complexity O(kLogk)
Explanation: 1) to sort the array firstly create a min-heap with first k+1 elements and a separate array as resultant array.
2) because elements are at most k distance apart from original position so, it is guranteed that the smallest element will be in this K+1 elements.
3) remove the smallest element from the min-heap(extract min) and put it in the result array.
4) Now,insert another element from the unsorted array into the mean-heap, now,the second smallest element will be in this, perform extract min and continue this process until no more elements are in the unsorted array.finally, use simple heap sort for the remaining elements
1) O(k) to build the initial min-heap
2) O((n-k)logk) for remaining elements…
3) 0(1) for extract min
so overall O(k) + O((n-k)logk) + 0(1) = O(nlogk)
Quiz of this Question
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.