priority queue min heap code example

Example 1: min heap in c++

priority_queue , greater> minHeap;

Example 2: min heap priority queue c++

#include
std::priority_queue , std::greater > minHeap;

Example 3: priority queue min heap

#include 
using namespace std;
 
// User defined class, Point
class Point
{
   int x;
   int y;
public:
   Point(int _x, int _y)
   {
      x = _x;
      y = _y;
   }
   int getX() const { return x; }
   int getY() const { return y; }
};
 
// To compare two points
class myComparator
{
public:
    int operator() (const Point& p1, const Point& p2)
    {
        return p1.getX() > p2.getX();
    }
};
 
// Driver code
int main ()
{
    // Creates a Min heap of points (order by x coordinate)
    priority_queue , myComparator > pq;
 
    // Insert points into the min heap
    pq.push(Point(10, 2));
    pq.push(Point(2, 1));
    pq.push(Point(1, 5));
 
    // One by one extract items from min heap
    while (pq.empty() == false)
    {
        Point p = pq.top();
        cout << "(" << p.getX() << ", " << p.getY() << ")";
        cout << endl;
        pq.pop();
    }
 
    return 0;
}

Example 4: create a min heap in java using priority queue

int arr[]={1,2,1,3,3,5,7};
        PriorityQueue a=new PriorityQueue<>();
        for(int i:arr){
            a.add(i);
        }
        while(!a.isEmpty())
            System.out.println(a.poll());

Example 5: priority queue max heap in java

//Sol1
PriorityQueue queue = new PriorityQueue<>(10, Collections.reverseOrder());


//Sol2
// PriorityQueue pq = new PriorityQueue<>((x, y) -> y - x);
PriorityQueue pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));


//Sol3
PriorityQueue pq = new PriorityQueue(defaultSize, new Comparator() {
    public int compare(Integer lhs, Integer rhs) {
        if (lhs < rhs) return +1;
        if (lhs.equals(rhs)) return 0;
        return -1;
    }
});

Example 6: Priority Queue using Min Heap in c++

#include 
using namespace std;
 

int main ()
{
   
    priority_queue  pq;
    pq.push(5);
    pq.push(1);
    pq.push(10);
    pq.push(30);
    pq.push(20);
 
   
    while (pq.empty() == false)
    {
        cout << pq.top() << " ";
        pq.pop();
    }
 
    return 0;
}

Tags:

Misc Example