Java implementation for Min-Max Heap?

允我心安 提交于 2019-11-27 11:02:36
Louis Wasserman

From Guava: MinMaxPriorityQueue.

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.

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<>((x,y) -> y-x);

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

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.

Nat

The java.util.TreeSet class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!