0

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
imgoingmad
  • 95
  • 3
  • 10

1 Answers1

1

I think you just need another variable keeping track of the index at which you found the key to swap with:

def downheap(A, i): 

    if A[i*2] > len(A):
        return

    bkIndex = i*2
    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
        bkIndex = i*2 + 1

    if A[i] < bk: #if parent is smaller than bk, swap parent with bk
       temp = bk
       bk = A[i]
       A[i] = temp
       downheap(A, bkIndex)

I haven't tested that the code works with this change, but hopefully this will help get you going in the right direction!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Yes, this solves using bk's index in downheap. But now I'm getting index errors, so I'm not certain my algorithm works too well... Something else to look at now. Thank you anyway. – imgoingmad Feb 07 '16 at 21:50