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)

**Answer:** **(B)** **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

Time Complexity

————————

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

## Recommended Posts:

- Algorithms | Sorting | Question 1
- Algorithms | Sorting | Question 2
- Algorithms | Sorting | Question 3
- Algorithms | Sorting | Question 4
- Algorithms | Sorting | Question 6
- Algorithms | Sorting | Question 7
- Algorithms | Sorting | Question 23
- Algorithms | Sorting | Question 9
- Algorithms | Sorting | Question 10
- Algorithms | Sorting | Question 11
- Algorithms | Sorting | Question 12
- Algorithms | Sorting | Question 13
- Algorithms | Sorting | Question 14
- Algorithms | Sorting | Question 15
- Algorithms | Sorting | Question 16
- Algorithms | Sorting | Question 17
- Algorithms | Sorting | Question 18
- Algorithms | Sorting | Question 19
- Algorithms | Sorting | Question 20
- Algorithms | Sorting | Question 23