Java implementation for Min-Max Heap?

Viewed 96279

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 minimum and maximum value in O(1) and to remove an element in O(log n)?

7 Answers

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<>(Collections.reverseOrder());

    // 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:

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.

Min Heap: PriorityQueue minHeap= new PriorityQueue<>();

Max Heap PriorityQueue maxHeap= new PriorityQueue<>(Comparator.reverseOrder());

Well you can simply pass the comparator to be used to compare elements. This will become useful even when you want to sort objects based on some attributes. Look at the following examples:

  • Min Heap :

    PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> a - b);
    

  • Max Heap :

    PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b - a);
    

  • Min Heap for Objects

    PriorityQueue<MyObject> pq = new PriorityQueue<>((obj1, obj2) -> obj1.getId() - obj2.getId());
    

  • Max Heap for Objects

    PriorityQueue<MyObject> pq = new PriorityQueue<>((obj1, obj2) -> obj2.getId() - obj1.getId());
    

Related