# Program to Find Out Median of an Integer Array in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have to implement a class named MedianClass which contains the following methods −

• add(value) which adds a value to the data structure.

• median() finds the median of all the numbers currently present in the data structure.

So, if we add 5, 3, 8 and find median, the output will be 5.0, then if we add 9 and find the median, the output will be 6.5.

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)/2Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef double lli;
class MedianClass {
priority_queue <int> left;
priority_queue <int, vector <int>, greater<int>> right;
public:
void addNum(int num) {
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(){
MedianClass ob;
cout << ob.findMedian() << " ";
cout << ob.findMedian() << endl;
}

## Input

ob.addNum(5);
cout << ob.findMedian() << endl;
5.0
6.5