public Comparable remove() {
if (size == 0) {
throw new NoSuchElementException();
}
Comparable result = heap[0];
Comparable item = heap[--size];
int child, parent = 0;
while ((child = (2 * parent) + 1) < size) {
if (child + 1 < size && heap[child].compareTo(heap[child + 1]) < 0) {
++child;
}
if (item.compareTo(heap[child]) < 0) {
heap[parent] = heap[child];
parent = child;
} else {
break;
}
}
heap[parent] = item;
return result;
}
|
If the heap is empty
(size == 0) an exception must be raised; otherwise the item to be returned is
heap[0] and the item to be reinserted is
heap[size-1], which we access as
heap[--size], thereby also decreasing the size of the heap. We begin with parent in the root position. The initial values of parent
and children are shown below.
child+1 < size). If so, it compares the values located at the two children and sets
child to be the location of the larger. The second if
statement then compares the item to be demoted with the value at
this child. If the item is strictly less than the value
at the child, the child value is promoted. Otherwise, we
are done and the item can be inserted in the parent
position. Finally we return the item of highest priority.