To Prove: There are at most 2l nodes at level l in a binary tree. By induction: Prove true for the base case At level 0 there are at most 20 = 1 Strong Induction: Assume true for k At level k there are at most 2k nodes. Prove for k+1 To show: At level k+ there are at most 2k+1 nodes. By the inductive step, there are at most 2k nodes at level k. Since it is a binary tree, each node at level k may have two children, so there are at most 2*2k nodes at level k+1. Since 2*2k = 2k+1 the proof is complete.
PARENT(i)Right(i)
- return i/2
PARENT(i)
- return i*2+1
- return i*2
HEAPIFY(A,i)
- l ← LEFT(i)
- r ← RIGHT(i)
- if l ≤ HEAP_SIZE(A) and A[l] > A[i] then
- largest ← l
- else
- largest ← i
- if r ≤ HEAP_SIZE(A) and A[r] > A[largest] then
- largest ← r
- if i ≠ largest then
- SWAP(A[i],A[largest])
- HEAPIFY(A,largest)
BUILD_HEAP(A)
- HEAP_SIZE(A) ← length[A] // perhaps an abuse of notation.
- for i ← ⌊length[A]/2⌋ down to 1 do
- HEAPIFY(A,i)
HEAPSORT(A)
- BUILD_HEAP(A)
- for i ← length[A] down to 2 do
- SWAP(A[1],A[i])
- HEAP_SIZE(A) ← HEAP_SIZE(A)-1 // perhaps an abuse of notation.
- HEAPIFY(A)
- return