Implement build-heap
Challenge · Write code · about 20 min
Rearrange values in place into a max-heap and return it. Every value must be at least as large as its children at 2i + 1 and 2i + 2.
Use the bottom-up method: sift down every parent, from the last one back to index 0. Any valid max-heap of the same values is accepted.
Example 1
Input:
[[4,1,3,2,16,9,10,14,8,7]]
Output:
[16,14,10,8,7,9,3,2,4,1]
The last parent is index 4. Seven swaps build the heap.
Example 2
Input:
[[1,2,3]]
Output:
[3,2,1]
1 swaps with its larger child 3.
Constraints
- 0 ≤ values.length ≤ 100,000
- Values are integers from -1,000,000 to 1,000,000
- Return the same values, rearranged
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
- Heapify Standard
- Count sift steps Standard
- Sift down one index Standard