The task is to find the kth smallest/largest element in an array.
This can be done through different methods which are discussed in detail below.
Method 1: By Sorting
This method is straight forward and can be used by shorting array and returning the kth smallest element.
Method 2: By using MAX heap
In this method, max heap of K elements is constructed and the next remaining elements from the array are checked. If the element is smaller than the root, it is made as root and heapify method is called. Finally, the root element of Max Heap is the kth smallest element.
Method 3: By using MIN heap
In this method, min heap is constructed and then the root element is removed k times to get the kth smallest element.
Each method has its time complexity which varies from O(nlogn) to O(k+(n-k)logk).