max heap using priority queue code example
Example 1: max heap java
import java.util.PriorityQueue;
public class MaxHeapWithPriorityQueue {
public static void main(String args[]) {
PriorityQueue<Integer> prq = new PriorityQueue<>(Comparator.reverseOrder());
prq.add(6);
prq.add(9);
prq.add(5);
prq.add(64);
prq.add(6);
while (!prq.isEmpty()) {
System.out.print(prq.poll()+" ");
}
}
}
Example 2: min heap priority queue c++
#include<queue>
std::priority_queue <int, std::vector<int>, std::greater<int> > minHeap;
Example 3: priority queue max heap in java
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<Integer> pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(defaultSize, new Comparator<Integer>() {
public int compare(Integer lhs, Integer rhs) {
if (lhs < rhs) return +1;
if (lhs.equals(rhs)) return 0;
return -1;
}
});
Example 4: Priority Queue using Min Heap in c++
#include <bits/stdc++.h>
using namespace std;
int main ()
{
priority_queue <int> 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;
}