Heapify
Standard · Trace the algorithm · about 8 min
Run build-heap on [3, 9, 2, 1, 4, 5, 8] to make a max-heap. Sift down index 2, then 1, then 0.
Predict the first swap, then arrange the array as it looks when build-heap finishes.
Example 1
Input:
{"values":[3,9,2,1,4,5,8]}
Output:
[9,4,8,1,3,5,2]
Index 2 is the last parent, so it is sifted first.
Constraints
- The trace uses the array shown
Learn the idea first: Building a heap in O(n), a visual lesson.
More Building a heap in O(n) problems
- Why is build-heap O(n)? Warm-up
- Is it a max-heap? Warm-up
- Count sift steps Standard
- Sift down one index Standard
- Implement build-heap Challenge