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.
Members only · free account
The rest of this lesson, with 7 more sections, 1 drawing, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson