How to find Kth smallest element of an array using heap:
#include <bits/stdc++.h>
using namespace std;
int main()
{ int a[10]={6,8,10,54,7,9,1,4,3,18}; //take user input array of size n
int k=4; //take user input as the position of the number you want to find.
priority_queue <int> maxheap;
for(int i=0;i<10;i++)
{
maxheap.push(a[i]);
if(maxheap.size()>k)
{
maxheap.pop();
}
}
cout<<maxheap.top();
return 0;
}
OUTPUT: 6
NOTE:
1. Max heap is implemented using priority_queue <data type> name in STL in cpp.
2. name.push() is to push push an element into the heap and name.pop() is to remove an element. name.top() returns the top element of the heap. [ same as stack]
3. Time complexity is O(n log k).
4. The size of the heap is maintained as K, if it exceeds K, then the excess elements are being popped. At the end, the top element gives us the Kth smallest number of the set as it is a max heap.
How to find Kth largest element of an array using heap:
#include <bits/stdc++.h>
using namespace std;
int main()
{ int a[10]={6,8,10,54,7,9,1,4,3,18}; //take user input array of size n
int k=3;
priority_queue <int, vector<int>, greater<int> > minheap; //take user input as the position of the number you want to find.
for(int i=0;i<10;i++)
{
minheap.push(a[i]);
if(minheap.size()>k)
{
minheap.pop();
}
}
cout<<minheap.top();
return 0;
}
0 Comments