Heaps: Find the Running Median

  • + 0 comments

    C++ Heaps Approach

    void runningMedian(vector<int> arr)
    {
        priority_queue<int, vector<int>> mxheap;
        priority_queue<int, vector<int>, greater<int>> minheap;
        float med = arr[0];
        mxheap.push(arr[0]);
         cout << fixed << setprecision(1) << med << endl;
        for (int i = 1; i < arr.size(); i++)
        {
    
            if (mxheap.size() == minheap.size())
            {
                // if (mxheap.size() == 0)
                // {
                //     mxheap.push(arr[i]);
                //     med = mxheap.top();
                //     cout << med << endl;
                //     return;
                // }
                if (arr[i] < mxheap.top())
                {
                    mxheap.push(arr[i]);
                    med = (double)mxheap.top();
                }
                else
                {
                    minheap.push(arr[i]);
                    med = (double)minheap.top();
                }
            }
            else
            {
                if (mxheap.size() > minheap.size())
                {
                    if (arr[i] >= mxheap.top())
                    {
                        minheap.push(arr[i]);
                    }
                    else
                    {
                        int temp = mxheap.top();
                        mxheap.pop();
                        mxheap.push(arr[i]);
                        minheap.push(temp);
                    }
                    med = (mxheap.top() + minheap.top()) / 2.0;
                }
                else
                {
                    if (arr[i] <= minheap.top())
                    {
                        mxheap.push(arr[i]);
                    }
                    else
                    {
                        int temp = minheap.top();
                        minheap.pop();
                        minheap.push(arr[i]);
                        mxheap.push(temp);
                    }
                    med = (mxheap.top() + minheap.top()) / 2.0;
                }
            }
            printf("%.1f \n",med);
        }
    }