package rebelsky.exam3; import java.util.Comparator; import java.util.Vector; /** * A simple (and currently incomplete) implementation of heaps. * * @author Samuel A. Rebelsky * @author YourNameHere */ public class Heap implements PriorityQueue { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** * The underlying vector that stores all the values. */ Vector contents; /** * The comparator used to determine ordering. */ Comparator order; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Build a new heap that uses a particular comparator to * determine ordering. */ public Heap(Comparator _order) { this.contents = new Vector(); this.order = _order; } // Heap(Comparator) // +----------------+------------------------------------------ // | Public Methods | // +----------------+ public void put(T element) throws Exception { // Put the new element at the end of the last row of the heap. this.contents.add(element); // Swap it up through the heap until it's in the correct place. this.swapUp(this.size()-1); } // put(T) /** * Remove the smallest value from the heap. */ public T get() throws Exception { // Remember what is at the root of the heap. T smallest = this.contents.get(0); // Put the last value at the root T tmp = this.contents.remove(this.size()-1); if (this.size() > 0) { this.contents.set(0,tmp); // Swap it down until its in the correct place. this.swapDown(0); } // Return what was at the root return smallest; } // get() public boolean isEmpty() { return (this.size() == 0); } // isEmpty() public boolean isFull() { return false; } // isFull() public int size() { return this.contents.size(); } // size() // +----------------+------------------------------------------ // | Helper Methods | // +----------------+ /** * Get the index of the left child. */ int left(int pos) { return 2*pos + 1; } // left(int) /** * Get the index of the right child. */ int right(int pos) { return 2*pos + 2; } // right(int) /** * Get the index of the parent. */ int parent(int pos) { if ((pos % 2) == 0) { return (pos-2)/2; } else { return (pos-1)/2; } } // parent(int) /** * Swap the value at position pos down through the heap until it * reaches the correct position. */ void swapDown(int pos) { // STUB } // swapDown(int) /** * Swap the value at position pos up through the heap until it * reaches the correct position. */ void swapUp(int pos) { // STUB } // swapUp(int) } // class Heap