I am attempting to downheap on an array from the last interior node all the way up to the root, so that I am making mini-heaps from the bottom up. I have an algorithm that I believe will do this though I far from 100% certain at this point, plus I'm having trouble implementing it.
The problem I have is with the recursive call. I would like the index to be the index of bk. I want to do this, but I am not sure how to. How should I tweak things?
#!/usr/bin/python
import random
random.seed()
def make_heap(A):
i = (len(A)-1)/2 - 1
while(i>-1):
downheap(A,i)
i -= 1
def downheap(A, i):
if A[i*2] > len(A):
return
bk = A[i*2] #set bk as left child (bk is biggest child)
if A[(i*2) + 1] <= len(A) and bk < A[(i*2) + 1]:
bk = A[(i*2) + 1] # if bk is less than right child, right child is bk
if A[i] < bk: #if parent is smaller than bk, swap parent with bk
temp = bk
bk = A[i]
A[i] = temp
downheap(A, i) #index of bk, not i??
def main():
L = []
size = 15
for i in range(size):
L.append(i)
random.shuffle(L)
print "Array: "
for i in range(size):
print str(L[i]),
make_heap(L)
print "\nHeap: "
for i in range(size):
print str(L[i]),
main()
Here is the output:
Array:
3 6 12 7 2 1 5 8 4 10 11 0 13 9 14
Heap:
13 13 12 13 10 11 13 8 4 10 11 0 13 9 14