Skip to content

Instantly share code, notes, and snippets.

@ahammar
Created June 10, 2011 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahammar/1020043 to your computer and use it in GitHub Desktop.
Save ahammar/1020043 to your computer and use it in GitHub Desktop.
Number of comparisons in build_heap
def parent(i):
return i/2
def left(i):
return 2*i
def right(i):
return 2*i+1
def heapify_cost(n, i):
most = 0
if left(i) <= n:
most = 1 + heapify_cost(n, left(i))
if right(i) <= n:
most = 1 + max(most, heapify_cost(n, right(i)))
return most
def build_heap_cost(n):
return sum(heapify_cost(n, i) for i in xrange(n/2, 1, -1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment