/** * CSE 373, Winter 2011, Jessica Miller * The IntBinaryHeap is an implementation of the IntPriorityQueue interface. * This is a binary heap implementation of the priority queue ADT. */ import java.util.Arrays; public class IntBinaryHeap implements IntPriorityQueue { private static final int DEFAULT_CAPACITY = 10; private int[] array; private int size; public IntBinaryHeap () { array = new int[DEFAULT_CAPACITY]; size = 0; } public void add(int value) { // grow array if needed if (size >= array.length - 1) { array = this.resize(); } // place element into heap at bottom size++; int index = size; array[index] = value; bubbleUp(); } public boolean isEmpty() { return size == 0; } public int peek() { if (this.isEmpty()) { throw new IllegalStateException(); } return array[1]; } public int remove() { // what do want return? int result = peek(); // get rid of the last leaf/decrement array[1] = array[size]; array[size] = 0; size--; bubbleDown(); return result; } public String toString() { return Arrays.toString(array); } private void bubbleDown() { int index = 1; while (hasLeftChild(index)) { // which of my children is smaller? int smallerChild = leftIndex(index); // bubble with the smaller child, if I have a smaller child if (hasRightChild(index) && array[leftIndex(index)] > array[rightIndex(index)]) { smallerChild = rightIndex(index); } if (array[index] > array[smallerChild]) { swap(index, smallerChild); } else { // otherwise, get outta here! break; } // make sure to update loop counter/index of where last el is put index = smallerChild; } } private void bubbleUp() { int index = this.size; while (hasParent(index) && (parent(index) > array[index])) { // parent/child are out of order; swap them swap(index, parentIndex(index)); index = parentIndex(index); } } private boolean hasParent(int i) { return i > 1; } private int leftIndex(int i) { return i * 2; } private int rightIndex(int i) { return i * 2 + 1; } private boolean hasLeftChild(int i) { return leftIndex(i) <= size; } private boolean hasRightChild(int i) { return rightIndex(i) <= size; } private int parent(int i) { return array[parentIndex(i)]; } private int parentIndex(int i) { return i / 2; } private int[] resize() { return Arrays.copyOf(array, array.length * 2); } private void swap(int index1, int index2) { int tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } }