//---------------------------------------------------------------------------- // Heap.java by Dale/Joyce/Weems Chapter 9 // // Defines all constructs for a heap. // The dequeue method returns the largest element in the heap. // // ajg-version: DWC, format, no ArrayList, no questionable casts //---------------------------------------------------------------------------- package ch09.priorityQueues; public class Heap> implements PriQueueInterface { private int lastIndex = -1; private int maxIndex; private T[] elements; public Heap(T[] elements) { // the Davis Weird Constructor DWC this.elements = elements; maxIndex = elements.length -1; } public boolean isEmpty() { return lastIndex == -1; } public boolean isFull() { return lastIndex == maxIndex; } public void enqueue (T element) throws PriQOverflowException { if (lastIndex == maxIndex) throw new PriQOverflowException("helpful message"); else { ++lastIndex; reheapUp(element); } } private void reheapUp(T element) { int hole = lastIndex; while ((hole>0) && (element.compareTo(elements[parent(hole)])>0)) { elements[hole] = elements[parent(hole)]; hole = parent(hole); } elements[hole] = element; } private int parent(int index) { return (index-1)/2; } public T dequeue() throws PriQUnderflowException{ if (lastIndex == -1) throw new PriQUnderflowException("Helpful msg"); T ans = (T)elements[0]; T toMove = (T)elements[lastIndex--]; if (lastIndex != -1) reheapDown(toMove); return ans; } private void reheapDown(T element) { int hole = 0; int newhole = newHole(hole, element); while (newhole != hole) { elements[hole] = elements[newhole]; hole = newhole; newhole = newHole(hole, element); } elements[hole] = element; } private int newHole(int hole, T element) { int left = 2 * hole + 1; int right = 2 * hole + 2; if (left > lastIndex) // no children return hole; if (left == lastIndex) // one child return element.compareTo(elements[left])<0 ? left : hole; if (elements[left].compareTo(elements[right]) < 0) return element.compareTo(elements[right])<0 ? right : hole; return element.compareTo(elements[left])<0 ? left : hole; } public String toString() { String theHeap = new String("The heap is\n"); for (int i=0; i<=lastIndex; i++) theHeap += i + ". " + elements[i] + "\n"; return theHeap; } } // Local Variables: // compile-command: "cd ../..; javac -Xlint:unchecked ch09/priorityQueues/Heap.java" // End: