In Java Software Structures 3rd Edition by Lewis and Chase the array implementation of a heap works for small numbers of items, but in cases with a large number of items sometimes throws a ArrayIndexOutOfBoundsException. It occurs in line 113 of the method heapifyRemove() in ArrayHeap (which extends ArrayBinaryTree).
Line 113:
if ((tree[left] == null) && (tree[right] == null))
It seems that left sometimes walks off the end of the array. How could this be fixed?
For reference:
Before checking if the index for left is null it should check if the the size of the array contains left (from how the array grows it looks like it would always include left and right). I think that case should be interpreted the same as if left and right are null.
So the the code should be