Programming assignment 4.
Implement a function to find the K elements of a given array that are closet to the median. (Hint: You could use Quick_Select to find the answer!)
- Request the user to enter a positive integer, and call it n.
- Generate n random integers between -100 to 100 and save them in a.
- Print the generated array.
- Request the user to enter a number between 1 to n, and call it K.
- Find the median of the array. (Hint: The time complexity in this step is O(n).)
- Save the differences from the median (a[i]-median) in a new array and call it diff. (Question: What is the time complexity in this stage?
- Use diff to find the K closest numbers.
(Hint Important:
The K closet elements have the K smallest absolute difference from the median.
Could you modify in your if/while statements of your partitioning step in your
QuickSelect? Maybe using absolute values? What is the time complexity in this step?)
- Shift the found K numbers back to their original value (+median). (Question: What is the time complexity in this step?)
- Print the answer
- Calculate the total time complexity of your algorithm and present your answer when demoing.
Example 1: Input: a = [10, 4, 2, 15, 18], K = 2
Output: 4, 15
Example 2: Input: a = [25, 3, 1, 8, 7, 2, 32], K = 4
Output: 1, 2, 3, 8
Reviews
There are no reviews yet.