Heaps: building, inserting, removing
A heap is stored as an array: the children of index i are at 2i + 1 and 2i + 2.
Rules
- Build-heap: sift down from the middle backwards
- Remove: move the last element to the front, sift down
- Insert: append, sift up
Your turn
Three problems on this topic. Separate lists with commas.
- 1 · Heap
- 2
- 3
Build a max-heap with build-heap (Floyd), then insert 74.
[26, 34, 15, 44, 19, 12, 33]
Heap after build-heap (comma-separated)
Heap after insertion (comma-separated)
Worked example
Build a max-heap with build-heap (Floyd), then insert 82.
[56, 18, 21, 14, 52, 12, 25, 44]
Worked solution
- 1Build-heap: sift down from the middle backwards: [56, 52, 25, 44, 18, 12, 21, 14]
- 2Afterwards: [82, 56, 25, 52, 18, 12, 21, 14, 44]
Typical mistake: When sifting down, always swap with the larger child.
Common questions
Why is build-heap O(n)?
Most nodes are near the bottom and sink only a little.
