Open In App

K-th Smallest Element in an Unsorted Array using Priority Queue

Last Updated : 16 Mar, 2023
Comments
Improve
Suggest changes
9 Likes
Like
Report

Given an array arr[] consisting of N integers and an integer K, the task is to find the Kth smallest element in the array using Priority Queue.

Examples:

Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 2
Output: 5
Explanation: In the given array, the 2nd smallest element is 5. Therefore, the required output is 5.

Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 5
Output: 20
Explanation: In the given array, the 5th smallest element is 20. Therefore, the required output is 20.

Approach: The idea is to use PriorityQueue Collection in Java or priority_queue STL library to implement Max_Heap to find the Kth smallest array element. Follow the steps below to solve the problem:

  1. Implement Max Heap using a priority_queue.
  2. Push first K array elements into the priority_queue.
  3. From there on, after every insertion of an array element, pop the element at the top of the priority_queue.
  4. After complete traversal of the array, print the element at the top of the priority queue as the required answer.

Below is the implementation of the above approach:

C++
// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to find kth smallest array element
void kthSmallest(vector<int>& v, int N, int K)
{
    // Implement Max Heap using
    // a Priority Queue
    priority_queue<int> heap1;

    for (int i = 0; i < N; ++i) {

        // Insert elements into
        // the priority queue
        heap1.push(v[i]);

        // If size of the priority
        // queue exceeds k
        if (heap1.size() > K) {
            heap1.pop();
        }
    }

    // Print the k-th smallest element
    cout << heap1.top() << endl;
}

// Driver code
int main()
{
    // Given array
    vector<int> vec = { 5, 20, 10, 7, 1 };

    // Size of array
    int N = vec.size();

    // Given K
    int K = 2;

    // Function Call
    kthSmallest(vec, N, K % (N+1));

    return 0;
}
Java Python3 C# JavaScript

Output: 
5

 

Time Complexity: O(N LogK)
Auxiliary Space: O(K), since the priority queue at any time holds at max k elements.


Next Article

Similar Reads