Max Heap Implementation

Is this implementation of max-heap correct?
https://github.com/ayush0605/Competitive-Programming/blob/master/Data_Structures/maxheap.cpp

Resizing vector like this is correct or there is fixed elements in a max heap

I want to know why are you implementing it when you already have priority queue in STL in c++.You can easily modify it to suit your purpose.

Can we use priority queue for negative values?

Yes :slight_smile:

Yes absolutely.priority queue by default is a max heap

So in case if we want to use min heap we have to just switch the sign of numbers?

No, just switch the comparator to std::greater:

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    priority_queue<int, vector<int>, greater<>> minHeap;
    for (int i = 0; i < 100; i++)
    {
        minHeap.push(rand() % 1000 - 500);
    }

    while (!minHeap.empty())
    {
        cout << minHeap.top() << endl;
        minHeap.pop();
    }
}
3 Likes

Thanks

1 Like