/** Heap class * Let's use an array, and logically start at index 0. * Then, child index values of a parent are 2p+1 and 2p+2. * In this heap, the lowest number is at the root. * Children must have values >= parent. */ public class Heap { private int a[]; private int maxSize; private int size; // Tells us how many values in heap. // Default constructor: create a logically empty heap // Let's assume 31 elements will suffice for later. public Heap() { maxSize = 31; a = new int[maxSize]; size = 0; } // From class notes: // To insert a node, make it the last child. // Heapify up as needed. Starting with c that we just inserted: // if value(c) >= value(parent(c)), done // else swap c with its parent and continue up. public void insert(int value) { // *** ADD CODE HERE } // From class notes: How to remove smallest element at the root. // Remove the root, and immediately replace it with the last child. // Heapify down as needed. Starting with root value r: // if value(r) <= values of both children, done. // else swap r with its SMALLER child and continue down. // What if a child is missing? // If there is only 1 child, just compare with it. // If there is no child, there would be nothing to swap with so halt. public int removeMin() { // *** ADD CODE HERE // I have a trivial return statement so the program will initially compile. // Please remove this statement before beginning your implementation. return 0; } public int findMin() { return a[0]; } public boolean isEmpty() { return size == 0; } // Print levels 0-4 of the heap, as needed. public String toString() { StringBuilder build = new StringBuilder(); for (int level = 0; level <= 4; ++level) { int leadingBlanks = (40 >> level) - 1; int blanksBetween = 2 * leadingBlanks; int startIndex = (1 << level) - 1; int upperIndex = (1 << (level+1)) - 2; for (int i = 0; i < leadingBlanks; ++i) build.append(" "); for (int i = startIndex; i <= upperIndex && i < size; ++i) { build.append("" + a[i]); for (int j = 0; j < blanksBetween; ++j) build.append(" "); } build.append("\n"); if (size <= upperIndex + 1) return build.toString(); } return build.toString(); // Java's "Must definitely return" } }