Describe an O(n)-time algorithm that, given a set S of n distinct numbers and a positive integer k≤n , outputs the k numbers in S that are closest to the median of S (excluding the median). Hint: The target numbers may not be evenly placed around the median in the sorted version of the array. E.g., consider 1,2,3,8,10; the 2 numbers closest to the median 3 are 1,2, excluding the median itself, but they are both less than the median. Note: this is just an illustration; don't assume that the array is sorted)
Here is the answer that I found link:
Answer: Find the n/2 − k/2 largest element in linear time. Partition on that element. Then, find the k largest element in the bigger subarray formed from the partition. Then, the elements in the smaller subarray from partitioning on this element are the desired k numbers.
My illustration:
Suppose I have an array with 11 elements and the array is an unsorted array
index_number 1 2 3 4 5 6 7 8 9 10 11
arr_elements 2 5 3 10 4 7 1 12 6 13 8
As there are 11 elements median should be 11/2= 5.5 approximately, 6. So arr_element 7 is the median. Now the solution said Find the n/2 − k/2 largest element in linear time
. Suppose k=4 so, k/4 = 2, therefore need to find out largest element from index 2 through index 6. The array elements from index 2 through 6 are {5,3,10,4,7}. So the largest element is 10. Now the answer said Partition on that element.
So there will be two sub array after partitioning from arr_element 10. The sub arrays are {2,5,3} and {4,7,1,12,6,13,8}. Then the answer said Then, find the k largest element in the bigger subarray formed from the partition.
k=4 so kth largest element means 4th largest element. The 4th largest element in the big subarray is 8. Now, the algorithm said Then, the elements in the smaller subarray from partitioning on this element are the desired k numbers.
I did not understand this statement.
The problem came from Cormen's Introduction to algorithm Chapter 9: Median and order statistics
Any hints would be appreciated.