I must be missing something very simple because this is blowing my mind!
I am trying to implement a Heap using a CompleteBinaryTree (which is implemented using an array). This CompleteBinaryTree is an array of Position<T>
where each Position
holds an element. I am writing the add(T t)
method for the Heap, where t
is inserted into the next free position of the CompleteBinaryTree, and then an upheap process is performed until the CompleteBinaryTree is ordered. Here is the method:
private CompleteBinaryTree<T> tree = new CompleteBinaryTree<T>();
private Position<T> entry = null;
public void add(T t) {
entry = tree.add(t);
if (entry.equals(tree.root())) {
return;
}
//continue to swap inserted element with its parent
//while it is smaller than its parent
while (entry.element().compareTo(tree.parent(entry).element()) < 0) {
Position<T> parent = tree.parent(entry);
Position<T> temp = entry;
entry = parent;
parent = temp;
}
}
The first element is added fine into the Heap, but when I try to add the second element, an InvalidPositionException
is thrown at the while()
line. This is where the exeption is being thrown from inside the CompleteBinaryTree class:
public Position<T> parent(Position<T> p) {
if (p == root()) throw new InvalidPositionException();
return array[((ArrayPosition) p).index/2];
}
And here are the two other methods used from CompleteBinaryTree
:
public Position<T> root() {
if (isEmpty()) throw new InvalidPositionException();
return array[1];
}
public Position<T> add(T t) {
if (last == array.length) {
// extend array
ArrayPosition[] temp = (ArrayPosition[]) new Object[array.length*2];
for (int i=1; i < array.length; i++) {
temp[i] = array[i];
}
array = temp;
}
array[last] = new ArrayPosition(last, t);
return array[last++];
}
How am I getting an exception thrown because p == root()
, when I first check if p is the root?
EDIT
Here is the CompleteBinaryTree toString()
, which is returned by the Heap toString()
:
public String toString() {
StringBuffer buf = new StringBuffer();
for (int i = 1; i < last; i++) {
buf.append(" ").append(array[i]);
}
return buf.toString();
}