The Max-Heapify
function may perform the following two comparisons at each execution, not taking into account the recursive call that follows:
B[left] > B[s]
and:
B[right] > B[s]
At each recursive call, we follow the sifted-down node, so the recursion tree has a maximum depth of ℎ+1, where ℎ is the height of the tree (expressed as the length of the longest path from the root). The deepest call will be on the leaf node which involves no (data) comparisons. So the maximum number of comparisons for one call of Max-Heapify
is 2ℎ.
I was wondering what's the max number of comparisons we have to make for a particular value in order to find it's final height.
The "particular value" is always the value at the root that is passed as argument to Max-Heapify
: this value sifts down to its final position. Any other value, that stands in the way of this sift-down process, moves up one level.
Could a leaf in the left-subtree end up as a leaf in the right subtree -> 2logn comparisons?
No, this is not possible. In one call of Max-Heapify
the root value can only move down, and any other value that has to move as a consequence, can only move up one level.
If we look at the total heap building process, which consists of several calls of Max-Heapify
, then consider that a node's value gets first
involved as the root node of a call of Max-Heapify
-- where it may move down, and only later may have to give way (for another value to sift down) and move up. It is not possible that a value first moves up, and then down. So it is excluded that a leaf value ends up in another leaf.
Let's look at the total number of comparisons during the heap building process:
The Max-Heap-Building
procedure executes Max-Heapify
first on the subtrees of height 1, then of those of height 2, ... up until the root. When the tree is a perfect binary tree, then at each increase of height we have half the number of subtrees to call Max-Heapify
with.
We can translate this observation into a recurrence relation. The maximum number of comparisons for a tree with height ℎ is:
This can be written as a closed expression:
If we use the number of nodes as parameter (instead of height ℎ), then for a perfect binary tree we have = 2ℎ+1-1, and the maximum number of comparisons for a perfect tree with nodes is:
As expected, this is O()