Why the Build Is Linear
The build sinks about internal nodes, and a sink runs at most the height of the tree, about steps, so a first estimate is . But almost no node sinks the full height of the tree.
Sink cost and node height
A sink moves a node down one level per step and stops at the bottom, so the most a node can sink is the number of levels beneath it, its height. The root can sink about levels. A node one level above the bottom can sink at most once, and a node on the bottom level cannot sink at all. Only the nodes near the top can sink far, and there are few of them: one root, two nodes below it, four below those. Most of the nodes are near the bottom, and they sink zero steps or one step.
Total sink work
Start with a perfect tree, where every level is full. Let be the number of nodes on the bottom level, the ones that do no sinking at all. Each level up holds half as many nodes as the level below it, so counting upward from the bottom:
- nodes sink steps.
- nodes sink at most step.
- nodes sink at most steps.
- nodes sink at most steps.
The total work is at most the sum, over the levels, of the number of nodes on the level times the most steps each of them sinks:
In the parentheses, the step count goes up by one each term, but the fraction of nodes halves. Call that sum , and subtract half of it, term by term:
So , and . The build does at most about steps.
Now, what is ? We do not need its exact value. The bottom level is part of the tree, so , and the build does at most steps:
A heap’s tree is complete, but it is not always perfect: its last level may be only partly filled. Picture filling that level in. The result is a perfect tree of the same height . Our complete tree has every level above the last full, which is nodes, plus at least one node on the last level, so . The filled-in tree has nodes, which is fewer than . Filling in gives every node at least as many levels beneath it as before, so the bound for the filled-in tree is at least the bound for ours. By the argument above, that bound is at most twice its node count, which is under . So the build is for every heap, perfect or not.
This bottom-up build is due to Robert W. Floyd, who published it in 1964, the same year J. W. J. Williams published heapsort. It is often called heapify, or Floyd’s method.
The sortdown
The sortdown does not get the same saving. It runs turns, and every turn sinks from the root, which has the whole heap beneath it. So each sink can take up to about steps, and the sortdown is . Add the build, and heapsort is .