Implement Max Heap
Build a max-heap from scratch: push, pop-max, and heapify on a plain array.
Intuition
A heap is a complete binary tree flattened into an array: children of i live at 2i+1 and 2i+2. Only one rule — parent ≥ children. Push bubbles a new leaf up; pop moves the last leaf to the root and sifts it down. Everything is swaps along one root-to-leaf path.
Approach
Array as tree
Completeness means no gaps: parent(i) = (i−1)//2. No pointers, great cache behaviour.
sift-up on push
Append at the end; swap with the parent while bigger than it. At most log n swaps.
sift-down on pop
Replace root with the last element; repeatedly swap with the larger child while smaller than it. Build-heap runs sift-down from n//2−1 backwards — O(n) total.
Solution & live demo
Edge cases
Root is the last element — remove and return, no sift.
≥ comparisons make ties stable enough; heap order tolerates equals on either side.