Mega Code Archive
Minimum heap implementation
/**
* Copyright (c) 2008-2010 Morten Silcowitz.
*
* This file is part of the Jinngine physics library
*
* Jinngine is published under the GPL license, available
* at http://www.gnu.org/copyleft/gpl.html.
*/
//package jinngine.util;
import java.util.*;
/**
* Minimum heap implementation. See [Cormen et al 1999] for formal theory.
* Maintains all elements in a min-heap, such that the minimum element will
* be the top-most node in the heap at all times. Among many other uses, heaps are ideal for
* representing priority queues.
*/
public class Heap {
private int size;
final private List heap;
final private Comparator comparator;
private class Node {
public T element;
public int position;
}
/**
* Create a new heap
* @param comparator A comparator that handles elements of type T
*/
public Heap( Comparator comparator ) {
size = 0;
//Allocate space
heap = new ArrayList();
//Comparator
this.comparator = comparator;
//initialy clear
//for (int i=0;i0) {
minHeapify( heap.get(0) );
}
return returnNode;
}
// private final void reinsert( final Node n ) {
// if ( !decreaseKey(n) ) {
// minHeapify(n);
// }
// }
public final int size() {
return size;
}
private final boolean decreaseKey( final Node node ) {
int index = node.position;
boolean modified = false;
// while ( index>0 && (heap[parent(index)]).compareTo( heap[index]) >= 0 ) {
while ( index>0 && comparator.compare(heap.get(parent(index)).element, heap.get(index).element ) >= 0 ) {
exchange( index, parent(index) );
index = parent(index);
modified = true;
}
return modified;
}
private final void minHeapify( final Node node ) {
int smallest;
int index = node.position;
int left = left(index);
int right = right(index);
// if (left iterator() {
return new Iterator() {
private Iterator iterator = heap.iterator();
@Override
public boolean hasNext() { return iterator.hasNext(); }
@Override
public T next() { return iterator.next().element; }
@Override
public void remove() { }
};
}
// public void printHeap() {
// int step =1;
// int i = 0;
// for (int n=0;n