Professional Documents
Culture Documents
@SuppressWarnings("unchecked")
public class Heap<AnyType extends Comparable<AnyType>>
{
private static final int CAPACITY = 2;
public Heap()
{
size = 0;
heap = (AnyType[]) new Comparable[CAPACITY];
}
/**
* Construct the binary heap given an array of items.
*/
public Heap(AnyType[] array)
{
size = array.length;
heap = (AnyType[]) new Comparable[array.length+1];
buildHeap();
}
/**
* runs at O(size)
*/
private void buildHeap()
{
for (int k = size/2; k > 0; k--)
{
percolatingDown(k);
}
}
private void percolatingDown(int k)
{
AnyType tmp = heap[k];
int child;
/**
* Sorts a given array of items.
*/
public void heapSort(AnyType[] array)
{
size = array.length;
heap = (AnyType[]) new Comparable[size+1];
System.arraycopy(array, 0, heap, 1, size);
buildHeap();
/**
* Deletes the top item
*/
public AnyType deleteMin() throws RuntimeException
{
if (size == 0) throw new RuntimeException();
AnyType min = heap[1];
heap[1] = heap[size--];
percolatingDown(1);
return min;
}
/**
* Inserts a new item
*/
public void insert(AnyType x)
{
if(size == heap.length - 1) doubleSize();
//Percolate up
for(; pos > 1 && x.compareTo(heap[pos/2]) < 0; pos = pos/2 )
heap[pos] = heap[pos/2];
heap[pos] = x;
}
private void doubleSize()
{
AnyType [] old = heap;
heap = (AnyType []) new Comparable[heap.length * 2];
System.arraycopy(old, 1, heap, 1, size);
}
public String toString()
{
String out = "";
for(int k = 1; k <= size; k++) out += heap[k]+" ";
return out;
}
h.insert("p");
h.insert("r");
h.insert("i");
h.insert("o");
System.out.println(h);
h.deleteMin();
System.out.println(h);