Created
June 10, 2011 23:54
-
-
Save ahammar/1020043 to your computer and use it in GitHub Desktop.
Number of comparisons in build_heap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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