forked from oviiii-m/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunningMedian.cpp
More file actions
60 lines (54 loc) · 1.29 KB
/
RunningMedian.cpp
File metadata and controls
60 lines (54 loc) · 1.29 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;
#include<queue>
void balanceHeap(priority_queue<int,vector<int>,greater<int>> &minHeap , priority_queue<int>&maxHeap)
{
int miSize = minHeap.size();
int mxSize = maxHeap.size();
if(abs(miSize - mxSize) >= 2)
{
if(miSize > mxSize)
{
maxHeap.push(minHeap.top());
minHeap.pop();
}
else
{
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
}
void findMedian(int arr[], int n){
priority_queue<int> max;
priority_queue<int,vector<int>,greater<int>> min;
for(int i=0;i<n;i++)
{
//Push the element
if(max.empty())
max.push(arr[i]);
else if(arr[i]>max.top())
min.push(arr[i]);
else
max.push(arr[i]);
//comparing sizes
balanceHeap(min,max);
//printing median
if(max.size()>min.size())
cout<<max.top()<<" ";
else if(min.size()>max.size())
cout<<min.top()<<" ";
else
cout<<(max.top()+min.top())/2<<" ";
}
}
int main() {
int n;
cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
findMedian(arr,n);
delete[] arr;
}