The top operation returns the element with the highest priority and removes it from a priority queue. In a heap, that element is stored at the root. section 2.4 section 2.6.4
Implement top on an array-backed heap by preserving the heap property after removing the root:
- Reject the operation when the heap is empty. section 2.6.4
- Save the root as the result, remove the last array element, and use that element to fill the root position. section 2.6.4
- Push the replacement downward until every parent-child relationship again satisfies the heap property. section 2.6.4
Task management
A priority queue containing bug reports returns “UI breaks on browser X” first at severity 9, then “CSS style causes misalignment” at severity 8. Each call to top removes its result, reducing the queue size from five to four and then three, regardless of insertion order. section 2.4.1
A heap requires at most logarithmically many swaps for top. For a d-ary heap, comparisons are approximately O(D·log_D(n)); increasing the branching factor reduces height but makes each level more expensive. Dynamic arrays provide an amortized logarithmic bound. section 2.10 section 2.6.4
Figure 2.10 Removing the top element from a binary heap. (A) From a valid ternary heap, we remove the root of the heap (storing it in a temporary location, in order to return it at the end). (B) We replace the old root with the last element in the array (which is also removed from its tail). The new root might violate heap’s properties (and it does, in this example), so we need to push it down, comparing it to its children to check that the heap’s properties are not violated. (C) We move the new root down toward the heap’s leaves, until we find a valid spot for it (that is, the first one that does not violate the heap’s properties).
Follow the root-removal sequence: save the top element, replace the root with the former last element, and push it down to a valid position. section 2.6.4

