Java implementation for Min-Max Heap?

前端 未结 5 1155
遥遥无期
遥遥无期 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<Integer> 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

    0 讨论(0)
  • 2020-12-02 09:18

    The java.util.TreeSet class.

    0 讨论(0)
  • 2020-12-02 09:19

    From Guava: MinMaxPriorityQueue.

    0 讨论(0)
  • 2020-12-02 09:19

    How about com.aliasi.util.MinMaxHeap? This is part of LingPipe; unfortunately, the licensing may be a problem.

    See this related paper.

    Doesn't implement decreaseKey or increaseKey, though.

    0 讨论(0)
  • 2020-12-02 09:20

    Instead of a max-min heap, could you use two instances of a java.util.PriorityQueue containing the same elements? The first instance would be passed a comparator which puts the maximum at the head, and the second instance would use a comparator which puts the minimum at the head.

    The downside is that add, delete, etc would have to be performed on both structures, but it should satisfy your requirements.

    0 讨论(0)
提交回复
热议问题