Skip to content

Commit 380f587

Browse files
Merge pull request #339 from gulshanyadav01/gulshan
k largest has been done
2 parents c0a7cd8 + 7f6d247 commit 380f587

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Heap/a.out

-32 Bytes
Binary file not shown.

Heap/kLargest.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
author:gulshan yadav
3+
email: gulshany01@gmail.com
4+
date: 21-July-2021
5+
*/
6+
#include<iostream>
7+
#include<bits/stdc++.h>
8+
using namespace std;
9+
10+
void kLargest(int arr[], int num, int k){
11+
12+
// build the min heap
13+
priority_queue<int, vector<int> , greater<int>> pq;
14+
15+
// bulid the heap for k elem
16+
for(int i = 0; i< k; i++){
17+
pq.push(arr[i]);
18+
19+
}
20+
21+
// go to the k+1 to the last
22+
for(int i = k; i< num ; i++){
23+
if(pq.top() > arr[i]){
24+
continue;
25+
}
26+
else {
27+
pq.pop();
28+
pq.push(arr[i]);
29+
}
30+
}
31+
32+
// print the elements of the min heap
33+
while(pq.empty() == false){
34+
cout << pq.top()<<" ";
35+
pq.pop();
36+
}
37+
38+
}
39+
40+
int main(){
41+
int num;
42+
cin >> num;
43+
int arr[num];
44+
for(int i = 0; i< num; i++){
45+
cin >> arr[i];
46+
}
47+
int k;
48+
cin >>k;
49+
kLargest(arr, num, k);
50+
return 0;
51+
52+
}

0 commit comments

Comments
 (0)