Java implementation for Min-Max Heap?

前端 未结 5 1183
遥遥无期
遥遥无期 2020-12-02 09:00

Do you know of a popular library (Apache, Google, etc, collections) which has a reliable Java implementation for a min-max heap, that is a heap which allows to peek its mini

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 09:17

    Java has good tools in order to implement min and max heaps. My suggestion is using the priority queue data structure in order to implement these heaps. For implementing the max heap with priority queue try this:

    import java.util.PriorityQueue;
    
    public class MaxHeapWithPriorityQueue {
    
        public static void main(String args[]) {
        // create priority queue
        PriorityQueue prq = new PriorityQueue<>((a,b)->b-a);
    
        // insert values in the queue
        prq.add(6);
        prq.add(9);
        prq.add(5);
        prq.add(64);
        prq.add(6);
    
        //print values
        while (!prq.isEmpty()) {
            System.out.print(prq.poll()+" ");
        }
        }
    
    }
    

    For implementing the min heap with priority queue, try this:

    import java.util.PriorityQueue;
    
    public class MinHeapWithPriorityQueue {
    
        public static void main(String args[]) {
            // create priority queue
            PriorityQueue< Integer > prq = new PriorityQueue <> ();
    
            // insert values in the queue
            prq.add(6);
            prq.add(9);
            prq.add(5);
            prq.add(64);
            prq.add(6);
    
            //print values
            while (!prq.isEmpty()) {
                System.out.print(prq.poll()+" ");
            }
        }
    
    }
    

    For more information, please visit:

    • https://github.com/m-vahidalizadeh/foundations/blob/master/src/data_structures/MaxHeapWithPriorityQueue.java

    • https://github.com/m-vahidalizadeh/foundations/blob/master/src/data_structures/MinHeapWithPriorityQueue.java

提交回复
热议问题