How does Java's PriorityQueue differ from a min-heap?

前端 未结 6 1922
时光取名叫无心
时光取名叫无心 2021-01-30 00:44

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

6条回答
  •  -上瘾入骨i
    2021-01-30 01:22

    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 
    

提交回复
热议问题