CS146
Chris Pollett
Feb 26, 2014
MAX-HEAPIFY(A,i) 1 l = LEFT(i) 2 r = RIGHT(i) 3 if l <= A.heap_size and A[l] > A[i] 4 largest = l 5 else largest = i 6 if r <= A.heap_size and A[r] > A[largest] 7 largest = r 8 if largest != i 9 exchange A[i] with A[largest] 10 MAX-HEAPIFY(A, largest)
BUILD-MAX-HEAP(A) 1 A.heap-size = A.length 2 for i = floor(A.length/2) downto 1 3 MAX-HEAPIFY(A, i)
At the start of each iteration of the for loop of lines 2-3, each node `i+1`, `i+2`, ..., `n` is the root of a max-heap.Proof.
We now give the pseudo-code for a sorting algorithm based on heaps. On the next slide we give some intuition and estimate its runtime.
HEAPSORT(A) 1 BUILD-MAX-HEAP(A) 2 for i = A.length downto 2 3 exchange A[1] with A[i] 4 A.heap-size = A.heap-size - 1 5 MAX-HEAPIFY(A, 1)
Below is max-heap pseudo-code for each of the priority queue operations. We give the run-times as comments.
HEAP-MAXIMUM(A) // This is an O(1) algorithm 1 return A[1]
HEAP-EXTRACT-MAX(A) // This is an O(log n) algorithm 1 if A.heap-size < 1 2 error "heap underflow" 3 max = A[1] 4 A[1] = A[A.heap-size] 5 A.heap-size = A.heap-size - 1 6 MAX-HEAPIFY(A,1) 7 return max
HEAP-INCREASE-KEY(A, i, key) // This is an O(log n) algorithm 1 if key < A[i] 2 error "new key is smaller than current key" 3 A[i] = key 4 while i > 1 and A[parent(i)] < A[i] 5 exchange A[i] with A[Parent(i)] 6 i = Parent(i)
MAX-HEAP-INSERT(A, key) // This is an O(log n) algorithm 1 A.heap-size = A.heap-size + 1 2 A[A.heap-size] = - infty 3 HEAP-INCREASE-KEY(A, A.heap-size, key)