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


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;
   ob.addNum(5);
   ob.addNum(3);
   ob.addNum(8);
   cout << ob.findMedian() << " ";
   ob.addNum(9);
   cout << ob.findMedian() << endl;
}

Input

ob.addNum(5);
ob.addNum(3);
ob.addNum(8);
cout << ob.findMedian() << endl;
ob.addNum(9);
cout << ob.findMedian() << endl;

Output

5.0
6.5

Updated on: 26-Dec-2020

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements