A max heap is a priority-queue structure in which larger priorities come first: every parent has a key greater than or equal to its children, so the maximum element remains at the root. It suits tasks where the next item must have the highest priority. section 2.5.4
A typical array-backed max heap supports these operations:
- Insert an element and restore heap order by moving it upward. section 2.6.4
- Read or remove the root with top(). Replace the root with the last array element, then push it down until the heap property is restored. section 2.6.4
- Choose a min heap instead when the smallest priority should be returned first; the implementations are symmetric, or priorities can be negated. section 2.5.4
Selecting the largest elements
To extract the largest k elements from a static set of n values, build a max heap with heapify in O(n), then call top() k times. This uses O(n) extra space and costs O(n + k log n). When n is much larger than k, a max heap is wasteful for this task: a size-k min heap keeps the largest values found so far and exposes the smallest retained value for replacement. section 2.7.1 section 2.7.2
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).
Trace root removal, replacement by the last array element, and pushDown through the heap until the new root reaches a valid position. section 2.6.4
