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
   /*@ post (\forall int j;
                  j ≥ 1 && j ≤ A.length;
                 A[ j ] ≥ A[left( j )] && A[ j ] ≥ A[right( j )]);     @*/
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⌋

Build-Max-Heap (A)
1 A.heap-size ← A.length
  /*@ loop-invariant \forall int j;
            i < j ≤ A.length;
           A[ j ] ≥ A[Left( j )] &&
                      A[ j ] ≥ A[Right( j )]
@*/ 
2 for i ← ⌊ A.length/2 ⌋ downto 1 do
3    Max-Heapify (A, i)
Max-Heapify (A, i)
1 l ← Left (i)
2 r ← Right (i)
3 if l ≤ A.heap-size and A[l] > A[i]
4    then largest ← l
5    else largest ← i
6 if r ≤ A.heap-size and A[r] > A[largest]
7    then largest ← r
8 if largest ≠ i then
9    exchange A[i] ↔ A[largest]
10    Max-Heapify (A, largest)


Proof of Correctness:


Running Time of Heapify (Build-Max-Heap)



T(n) =

 

=

 

=
but

using formula A.8 and

for x = 1/2 < 1

= 2 and O(2n) = O(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)?