# Find Median from Data Stream in C++

C++Server Side ProgrammingProgramming

Suppose we have a data stream, in that stream some data element may come and join, we have to make one system, that will help to find the median from the data. As we know that the median is the middle data of a sorted list, if it list length is odd, we can get the median directly, otherwise take middle two elements, then find the average. So there will be two methods, addNum() and findMedian(), these two methods will be used to add numbers into the stream, and find the median of all added numbers

To solve this, we will follow these steps −

• Define priority queue left and right

• Define addNum method, this will take the number as input −

• if left is empty or num < top element of left, then,

• insert num into left

• Otherwise

• insert num into right

• if size of left < size of right, then,

• temp := top element of right

• delete item from right

• insert temp into left

• if size of left – size of right > 1, then,

• temp := top element of left

• delete item from left

• insert temp into right

• Define findMedian() method, this will act as follows −

• return top of left if size of left > size of right, else (top of left + top of right)/2

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef double lli;
class MedianFinder {
priority_queue <int> left;
priority_queue <int, vector <int>, greater<int>> right;
public:
if(left.empty() || num<left.top()){
left.push(num);
}else right.push(num);
if(left.size()<right.size()){
lli temp = right.top();
right.pop();
left.push(temp);
}
if(left.size()-right.size()>1){
lli temp = left.top();
left.pop();
right.push(temp);
}
}
double findMedian() {
return
left.size()>right.size()?left.top():(left.top()+right.top())*0.5;
}
};
main(){
MedianFinder ob;
cout << ob.findMedian() << endl;
cout << ob.findMedian() << endl;
cout << ob.findMedian();
}

## Input

addNum(10);
findMedian();
findMedian();
12.5
25