Hints for implementing a heap using an array: --------------------------------------------- - When you use an array rather than a tree to implement a heap, you can do put's and get's more easily. In fact, you don't even need the decoder that translates tree positions into sequences of left and rights. - To put object o into position 13 of the heap, you simply store object o into the array at offset 13. Then, walk up the heap from position 13, swapping objects in a node and its parent as needed to restore the heap property. So, once the object o is stored into array offset 13, you compare the objects in location 13 with the object in location 13/2 = 6, and swap as needed; if you swapped, you then look at locations 6 and 6/2 = 3, and swap as needed; if you swapped, look at locations 3 and 3/2 = 1 and swap as needed. In other words, think about bubbling up the heap, which is easier than going down the heap. You can't do this with heaps implemented as trees very easily, but with an array, it is very easy. - Doing a get is also easier in the array. Once the object in the root is removed (array location 1), you simply access the object in the last filled position in the array (isn't random access nice?), put that into the root (location 1 of array), and then trickle-down as before when the heap was implemented as a tree. - The decoder I used in my heap implementation works but it is non-standard. Here is a class that implements the standard encoding/decoding described in lecture (the children of node i are at 2*i and 2*i + 1). To decode the path for position 13 in a binary tree, create a heapDecoder object by calling the constructor heapDecoder(13, 2). Use it if you want to use decoders with your array implementation, but you will find it much simpler to do put's and get's as described above. protected class heapDecoder { protected int position; protected int base; protected int cursor; public heapDecoder(int pos, int base){ position = pos; this.base = base; //initialize cursor to point to digit immediately to right //of most significant digit cursor = (int)(Math.log(pos)/Math.log(base)) - 1; } public int getNextDigit() { return (int)(position/Math.pow(base,cursor--)) % base ; } public boolean hasMoreDigits() { return (cursor >= 0); } }