Chapter 6 - Build Heap |
Document last modified: |
Build-Max-Heap
| Build-Max-Heap (A) -- alters A -- post: the tree rooted at location 1 in A satisfies the heap property
|
||
| 1 | A.heap-size ← A.length | |
| 2 | for i ← ⌊ A.length/2 ⌋ downto 1 do // start with last parent | |
| 3 | Max-Heapify (A, i) // and heapify back to root | |
Example - Building a max-heap from the following unsorted array results in the first heap example.
A.length = 10
i starts at 5, the last parent in the array: always at ⌊ n/2 ⌋
Max-Heapify is applied to subtrees rooted at nodes (in order): 16, 2, 3, 1, 4.
Note that Max-Heapify is run on each node that is a parent:
starts with the last parent in the array: always at ⌊n/2⌋
|
|
||||||||||||||||||||||||||||||||

Proof of Correctness:
//@ forall int j; i < j ≤ A.length; A[ j ] ≥ A[Left( j )] && A[ j ] ≥ A[Right( j )] for i ← ⌊A.length/2⌋ downto 1 do
Max-Heapify ( A, i )

| //@ forall int j; i < j ≤
A.length; A[ j ] ≥
A[Left( j )] &&
A[ j ] ≥
A[Right( j )] for i ← ⌊A.length/2⌋ downto 1 do
|
| //*@ post (\forall int j; j ≥ 1 && j ≤ A.length; A[ j ] ≥ A[left( j )] && A[ j ] ≥ A[right( j )]); |
Running Time of Heapify (Build-Max-Heap)
Question 6.5 - What does O(n lg n) assume in terms of the Max_Heapify tree height?

- Note the following facts:
- height of a node is the number of edges in the longest path from that node to a leaf
- full tree - each node is either a leaf or has degree exactly 2
- height of n-element heap = ⌊ lg n ⌋
- maximum number of nodes at any height h = ⌈n / 2h+1⌉ when n = # of nodes in a full tree
- tree above for height h = 3 is: ⌈ 15/23+1 ⌉ = 1, height h = 0 is: ⌈15/20+1⌉ = 8
- Heapify
- Sum up the cost of all the trips through the loop.
- c*h is the cost of Max-Heapify on a node at height h
| T(n) = |
|
= | ![]() |
| = | ![]()
|
= | |
| but |
using formula A.8 and for x = 1/2 < 1 |
= 2 | and O(2n) = O(n) |
- Revisited Simple Upper Bound - Applying loop analysis to get a simple upper bound:
- The number of times through the loop is ⌊n/2⌋ or O(n)
- Max-Heapify T(n) = Θ(lg n)
- Build-Max-Heap T(n) = O(n lg n)
Question 6.6
We determined a simple upper bound of
T(n) = O(n lg n)
and tightened the bounds to
T(n) = O(n)
Think about what happens to the depth with each application of Max-Heapify. What simplifying assumption did we make to come up with
T(n) = O(n lg n)?