python - Downheaping from an interior node with a recursive call to the index of the biggest child? -
i attempting downheap on array last interior node way root, making mini-heaps bottom up. have algorithm believe though far 100% @ point, plus i'm having trouble implementing it.
the problem have recursive call. index index of bk. want this, not sure how to. how should tweak things?
#!/usr/bin/python import random random.seed() def make_heap(a): = (len(a)-1)/2 - 1 while(i>-1): downheap(a,i) -= 1 def downheap(a, i): if a[i*2] > len(a): return bk = a[i*2] #set bk left child (bk biggest child) if a[(i*2) + 1] <= len(a) , bk < a[(i*2) + 1]: bk = a[(i*2) + 1] # if bk less right child, right child bk if a[i] < bk: #if parent smaller bk, swap parent bk temp = bk bk = a[i] a[i] = temp downheap(a, i) #index of bk, not i?? def main(): l = [] size = 15 in range(size): l.append(i) random.shuffle(l) print "array: " in range(size): print str(l[i]), make_heap(l) print "\nheap: " in range(size): print str(l[i]), main()
here 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
i think need variable keeping track of index @ found key swap with:
def downheap(a, i): if a[i*2] > len(a): return bkindex = i*2 bk = a[i*2] #set bk left child (bk biggest child) if a[(i*2) + 1] <= len(a) , bk < a[(i*2) + 1]: bk = a[(i*2) + 1] # if bk less right child, right child bk bkindex = i*2 + 1 if a[i] < bk: #if parent smaller bk, swap parent bk temp = bk bk = a[i] a[i] = temp downheap(a, bkindex)
i haven't tested code works change, going in right direction!
Comments
Post a Comment