Objective : Given an array of integers. find the K^{th} Smallest/largest element in the array.

Example :
int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 };
K=4. 4^{th} smallest element in given array: 10
Approach : (K^{th} Smallest Element)

Use min-Heap. (Click here to read about Priority Queue ).
Insert all the elements in the Priority Queue.
Extract K elements from the priority queue. The last element (k^{th} ) extracted with be the k^{th} smallest element in the array.
Complete Code: Run This Code

Run This Code

Output:
4th smallest element:10
Note: For k^{th} largest element, implement priority queue for max-Heap.

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

Like this: Like Loading...