binary heap

A binary heap is an array that implicitly represents a complete binary tree by virtue of its positions. A Max heap keeps the highest value at the lowest position, while a min heap keeps the lowest value at the lowest position.

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

    def percUp(self, i):
        # starting form last index, divide 2 to get to the beginning
        while i // 2 > 0:
            if self.heapList[i] < self.heapList[i // 2]: 
                tmp = self.heapList[i // 2]
                self.heapList[i // 2] = self.heapList[i]
                self.heapList[i] = tmp
            i = i // 2

    def insert(self, k):
        self.heapList.append(k)
        self.size = self.size + 1
        self.percUp(self.size)
        

    def minChild(self, i):
        # if i*2 + 1 (position of second child) is greater than size
        # return first child bc means there is no second child
        if (i*2 + 1) > self.size:
            return i * 2
        else:
            if self.heapList[i*2] < self.heapList[i*2 + 1]:
                return i*2
            else:
                return i*2 + 1

    def percDown(self, i):
        # i*2 is first child of i. i * 2 must be greater than size
        # for there to be no first child
        # only percDown if at least one child
        while i * 2 <= self.size:
            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 delMin(self):
        retval = self.heapList[1]
        self.heapList[1] = self.heapList[self.size]
        self.heapList.pop()
        self.size = self.size - 1
        self.percDown(1)
        return retval

    def buildHeap(self, alist):
        self.size = len(alist)
        self.heapList = [0] + alist[:]
        i = len(alist) // 2

        while i > 0:
            self.percDown(i)
            i = i - 1