views:

1444

answers:

3

Do you know of a popular library (apache collections, google collections, etc...) which has a reliable Java implementation for a Min-Max heap?

I.e. a heap which allows to peek at its minimum and maximum value in O(1) and to remove at O(logn).

I did a quick search and couldn't find one. Anyone know better?

A: 

The java.util.TreeSet class.

Nat
I need support for duplicate values... Set is "a bit" problematic in this aspect.
Yuval A
-1 TreeSet implements most operations in O(log n) - the requirement was for peeking at the minimum and maximum in O(1).
Avi
TreeSet also doesn't have a decreaseKey or increaseKey operation, which is one of the definitive operations of a heap. See http://en.wikipedia.org/wiki/Heap_(data_structure)
NamshubWriter
If you need to support duplicate values, you can use TreeBag (http://commons.apache.org/collections/api-release/org/apache/commons/collections/bag/TreeBag.html) from Apache Commons Collections, or TreeMultiset (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/TreeMultiset.html) from Google Collections. If you need to increaseKey or decreaseKey, you can simply remove the element and re-add it.
newacct
Or use a TreeMap that maps keys to counts. TreeSet is actually implemented with a TreeMap under the hood.
Nat
-1. TreeSet/TreeMap is a red-black tree, not a heap.
dty
+2  A: 

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.

NamshubWriter
+1  A: 

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.

Il-Bhima
+1. This is a good answer given the stated requirements to peek the root in O(1) and remove it in O(log.n). Note however, that a PriorityQueue doesn't implement all heap operations (e.g. decreaseKey, increaseKey).
dty