0

I am wondering in the following code,

In the code below i is set to min child, why is this done instead of say just having i = i*2. Both ways 'lower' the level of the binary heap, I am just curious as to why the minimum would be chosen (Assuming both children are NOT smaller than parent, why is the smaller of the two larger children chosen instead of one of them arbitrarily)

To be clear these methods below also belong to the binaryheap class

def percDown(self,i):
  while (i * 2) <= self.currentSize:
    mc = self.minChild(i)
    if self.heapList[i] > self.heapList[mc]:
      tmp = self.heapList[i]
      self.heapList[i] = self.heapList[mc]
      self.heapList[mc] = tmp
    i = mc

def minChild(self,i):
  if i * 2 + 1 > self.currentSize:
    return i * 2
  else:
    if self.heapList[i*2] < self.heapList[i*2+1]:
      return i * 2
    else:
      return i * 2 + 1

The code for the binary heap class is

class BinHeap:
    def __init__(self):
        self.heapList = [0]
        self.currentSize = 0

    def delMin(self):
        retval = self.heapList[1]
        self.heapList[1] = self.heapList[self.currentSize]
        self.currentSize = self.currentSize - 1
        self.heapList.pop()
        self.percDown(1)
        return retval
  • 1
    Can you explain what the above code suppose to achieve? Without that information how can someone explain what is the purpose of setting i to the min child? – kosnik Jul 04 '18 at 11:22
  • The above code is designed to remove the minimum node from a binary heap (root), by swapping it with the lowest node and sinking it through the heap until its in the correct position. – adudelearning Jul 04 '18 at 11:40
  • I added some additional code to make it clearer. – adudelearning Jul 04 '18 at 11:40

0 Answers0