Visualize Max Heap operations step by step. Watch bubble-up on Insert, sift-down on Extract-Max, and O(1) Peek, with animated tree and array views.
About this algorithm
A max heap keeps the largest value at the root of a complete binary tree: every parent is greater than or equal to its children. It hands you the maximum at once, and after you remove it, the next largest rises to the top in O(log N) swaps. It is the priority queue to use when bigger means more urgent.
Use a max heap when the largest item must come out first: the highest bid, the most frequent word, the job with the top priority, or the k smallest values of a stream (keep a max heap of size k and evict its root whenever a smaller value arrives). Heap sort runs on a max heap too, moving the root to the back of the array again and again until the array is sorted ascending, with no extra memory. Pick a min heap for smallest-first work such as shortest paths, timers and meeting rooms. In a language whose heap is min-only, such as Python's heapq, push each value negated to get a max heap.
Peek returns index 0, the largest value, without changing anything.
To extract, remember the root, swap it with the value in the last slot and cut that slot off. The array is one shorter, and a small value now sits on top.
Compare the top value with both children. If either is larger, swap it with the larger of the two; swapping with the smaller one would put a smaller value above a larger one. Repeat until both children are smaller or equal, or there are none.
A new value goes at the end of the array and swaps with its parent while it is larger, stopping below the first parent that is larger or equal.
The page loads [20, 15, 18, 10, 12, 14, 9]: 20 at the root, 15 and 18 below it, 10 and 12 under 15, 14 and 9 under 18. Play runs Extract-Max, and 20 is the answer. The last value, 9, moves to the root and the array shrinks to six. 9 meets children 15 and 18; the larger is 18, so they swap. At index 2, 9 meets its one child, 14, which is larger, so they swap again. 9 is now a leaf and the heap reads [18, 15, 14, 10, 12, 9]. Extract again and 18 comes out, then 15: the values leave in descending order. Inserting 19 into the original heap shows the climb instead: it starts under 10, passes 10 and then 15, and stops under 20, giving [20, 19, 18, 15, 12, 14, 9, 10].
Each extract frees the last slot of the array, and the value just removed is the largest one left. Dropping it into that slot fills the array from the back with the largest values first, so the finished array is sorted ascending in place. A min heap would fill the back with the smallest values and leave the array in descending order.
Time: peek is a single read; extract and insert each swap at most once per level of a tree that is about log₂ N levels tall. Space: the heap is the array itself, N values, and sifting needs only a couple of index variables.