Why did they name PriorityQueue
if you can\'t insertWithPriority? It seems very similar to a heap. Are there any differences? If no difference, the
From Java docs
Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The priority queue is ordered by comparator, or by the elements' natural ordering.
Here is a working code for maxHeap and minHeap using PriorityQueue
-
class HeapDemo {
private final static int HEAP_SIZE = 10; //size of heap
//INNER CLASS
static class maxHeapComparator implements Comparator {
@Override
public int compare (Integer x, Integer y) {
return y-x; //reverse order
}
}
public static void main(String[] args) {
PriorityQueue minHeap = new PriorityQueue<>(HeapDemo.HEAP_SIZE);
PriorityQueue maxHeap = new PriorityQueue<>(HeapDemo.HEAP_SIZE, new maxHeapComparator());
for(int i=1; i<=HeapDemo.HEAP_SIZE; ++i){
int data = new Random().nextInt(100) +1; //number between 0 to 100
minHeap.add(data);
maxHeap.add(data);
}
System.out.print("\nMIN Heap : ");
Iterator iter = minHeap.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}
System.out.print("\nMAX Heap : ");
iter = maxHeap.iterator();
while(iter.hasNext()) {
System.out.print(iter.next() + " ");
}
}
}
sample o/p :
MIN Heap : 20 32 37 41 53 91 41 98 47 86
MAX Heap : 98 91 41 53 86 20 37 41 32 47