jayati

Find median in a stream

Mar 20th, 2024
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6.  
  7. // } Driver Code Ends
  8. class Solution
  9. {
  10.     public:
  11.     //Function to insert heap.
  12.     priority_queue<int> s;
  13.     priority_queue<int,vector<int>,greater<int>> g;
  14.     void insertHeap(int &x)
  15.     {
  16.         if(s.size()==0)
  17.         {
  18.             s.push(x);
  19.             return;
  20.         }
  21.         if(s.size()>g.size())
  22.         {
  23.             if(x<s.top())
  24.             {
  25.                 g.push(s.top());
  26.                 s.pop();
  27.                 s.push(x);
  28.             }
  29.             else
  30.             {
  31.                 g.push(x);
  32.             }
  33.         }
  34.         else
  35.         {
  36.             if(x<s.top())
  37.             {
  38.                 s.push(x);
  39.             }
  40.             else
  41.             {
  42.                 g.push(x);
  43.                 s.push(g.top());
  44.                 g.pop();
  45.             }
  46.         }
  47.        
  48.     }
  49.    
  50.     //Function to balance heaps.
  51.     void balanceHeaps()
  52.     {
  53.        
  54.     }
  55.    
  56.     //Function to return Median.
  57.     double getMedian()
  58.     {
  59.         if(s.size()==g.size())
  60.         {
  61.             return (double)(s.top()+g.top())/2.0;
  62.         }
  63.         else
  64.         {
  65.            
  66.             return s.top();
  67.         }
  68.     }
  69. };
  70.  
  71.  
  72. //{ Driver Code Starts.
  73.  
  74. int main()
  75. {
  76.     int n, x;
  77.     int t;
  78.     cin>>t;
  79.     while(t--)
  80.     {
  81.         Solution ob;
  82.         cin >> n;
  83.         for(int i = 1;i<= n; ++i)
  84.         {
  85.             cin >> x;
  86.             ob.insertHeap(x);
  87.             cout << floor(ob.getMedian()) << endl;
  88.         }
  89.     }
  90.     return 0;
  91. }
  92. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment