Skip to content

Commit f35eb3e

Browse files
Kth smallest element using a heap
1 parent 973a73b commit f35eb3e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**************************************************************************
2+
Given an array arr[] and a number K where K is smaller than size of array,
3+
the task is to find the Kth smallest element in the given array.
4+
Given all Array elements are distinct.
5+
6+
For Example: arr[] = {7, 8, 1, 4, 9, 3}
7+
k = 3 ------> 3rd smallest element in the array
8+
ANS: 4
9+
10+
This can be solved using heap and priority queue.
11+
***************************************************************************/
12+
13+
SOLUTION (in C++):
14+
15+
#include<bits/stdc++.h>
16+
17+
using namespace std;
18+
19+
int main()
20+
{
21+
int n, k;
22+
cin>>n>>k;
23+
cout<<"Enter the array elements"<<endl;
24+
int arr[n];
25+
priority_queue<int> maxh;
26+
//A priority queue keeps the elements in the order of their priority, i.e.,
27+
//elements having greater values will be at the top of the queue and elements having smaller values will be kept at the bottom of the queue.
28+
//The element popped out of this queue is the element with the maximum value.
29+
30+
for(int i = 0;i<n;i++){
31+
maxh.push(arr[i]);
32+
if(maxh.size() > k){
33+
maxh.pop();
34+
}
35+
}
36+
37+
cout<<"The "<<k<<"th smallest element is "<<maxh.top();
38+
return 0;
39+
}

0 commit comments

Comments
 (0)