Sift down one index
Standard · Write code · about 12 min
In values, the subtrees below index i are already max-heaps, but values[i] may be too small. Sift it down: while it is smaller than its larger child, swap the two. When both children are equal, use the left child.
Return the array after the sift.
Example 1
Input:
[[2,9,7,4,8,1,3],0]
Output:
[9,8,7,4,2,1,3]
2 swaps with 9, then with 8, and lands on a leaf.
Example 2
Input:
[[5,3,1],1]
Output:
[5,3,1]
Index 1 has no children, so nothing moves.
Constraints
- 0 ≤ values.length ≤ 10,000
- 0 ≤ i < values.length (i = 0 when the array is empty)
- The subtrees of i are max-heaps
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
- Implement build-heap Challenge