how to create max heap in java 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 max heap java
PriorityQueue<Integer> prq = new PriorityQueue<>();
PriorityQueue<Integer> prq = new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> prq = new PriorityQueue<>((a, b) -> b - a);