# Find the Kth Smallest/Largest Element in an Array

Objective: Given an array of integers. find the Kth Smallest/largest element in the array.

```Example:

int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 };

K=4. 4th smallest element in given array: 10
```

Approach: (Kth Smallest Element)

• Insert all the elements in the Priority Queue.
• Extract K elements from the priority queue. The last element (kth) extracted with be the kth smallest element in the array.

Complete Code:

```Output:
4th smallest element:10
```

Note: For kth 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.
__________________________________________________

### 4 Responses

1. Kamal Chaya says:

Is it faster to use hte quickselect algorithm ?

2. eugen_nw says:

It is also possible to just sort the input array in ascending order and pick the k-1th element.

• dogbert82 says:

That will take O(n) time. Idea here is to not sort the entire array. We can use priority queue or quick sort (i.e. partition only k times) and pivot will land in its correct position.

• gau246 says:

Why not just use Arrays.sort() and pick the k-1 th element?

This site uses Akismet to reduce spam. Learn how your comment data is processed.