Open in App
Not now

# Algorithms | Sorting | Question 5

• Difficulty Level : Hard
• Last Updated : 20 Oct, 2021

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?

(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:

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.

Time Complexity:

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

My Personal Notes arrow_drop_up
Related Articles