-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find median in a stream (IMP)(GFG).cpp
77 lines (57 loc) · 1.77 KB
/
Find median in a stream (IMP)(GFG).cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution
{
public:
//Function to insert heap.
// need to create two containers
// one smaller(max heap)
// another greater (min heap)
// these both will be implemented through priority queue
// max_heap will contain the extra element (median)
// if size is eqaul then take median
priority_queue<int> s;
priority_queue<int,vector<int>, greater<int>> g; //syntax for min_heap
int size=0;
void insertHeap(int &x)
{
// we need to check ki insert kis container me krna hai
// it's mainly depend upon the size of container
// [ we want that extra element to be inserted innto the smaller one]
// case 1: size small < greater size
if(size==0){
s.push(x);
}else{
if(s.size() > g.size()){
if(x < s.top()){
g.push(s.top());
s.pop();
s.push(x);
}else{
g.push(x);
}
}else{
if(x > s.top()){
g.push(x);
int t= g.top();
g.pop();
s.push(t);
}else{
s.push(x);
}
}
}
size++;
}
//Function to balance heaps.
// void balanceHeaps()
// {
// }
//Function to return Median.
double getMedian()
{
if(size%2!=0){
return (double)s.top();
}else{
return (s.top() + g.top())/2.0;
}
}
};