-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathNearlySortedAlgorithm.cpp
More file actions
45 lines (41 loc) · 1012 Bytes
/
NearlySortedAlgorithm.cpp
File metadata and controls
45 lines (41 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//Array and heap interview problem
//contributing for hacktoberfest2021
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int>kSort(int arr[], int n, int k){
priority_queue<int, vector<int>, greater<int>>min_heap;
vector<int>v;
for(int i=0; i<n; i++){
min_heap.push(arr[i]);
if(min_heap.size()>k){
v.push_back(min_heap.top());
min_heap.pop();
}
}
while(min_heap.size()>0){
v.push_back(min_heap.top());
min_heap.pop();
}
return v;
}
};
int main(){
int t;
cin >> t;
while(t--){
int n, k;
cin >> n >> k;
int arr[n];
for(int i = 0; i < n;i++)
cin>>arr[i];
Solution ob;
vector<int> result = ob.kSort(arr, n, k);
for (int i = 0; i < result.size(); ++i)
cout<<result[i]<<" ";
cout << endl;
}
return 0;
}