AlgoFrames

Count sift steps

Standard · Trace the algorithm · about 8 min

Build-heap turns [5, 3, 8, 4, 1, 7, 2, 9, 6] into a max-heap. One sift step is one swap of a value with its larger child.

Count the swaps as the trace plays.

Example 1

Input:

{"values":[5,3,8,4,1,7,2,9,6]}

Output:

5

The last parent is index 3, which holds 4.

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