Every heap operation follows the same plan. First make the change at the one place that keeps the tree complete: the end of the array. Then repair the order rule along a single path between the root and a leaf. A complete tree with n nodes is only about log₂ n levels tall, so that repair costs O(log n).
Only the new value's path to the root can break the order rule, and every swap moves a smaller value up past a bigger one — so each swap fixes the order where it happens, and nothing else has to move.
Free account
Sign up to read the rest of this lesson: 7 more sections, 1 drawing, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come