最小二叉堆

class BinaryHeap(object):

    """
    docstring for BinaryHeap
    二叉堆依靠完全二叉树实现,父节点(索引)为p,则左子树在2p,右子树在2p+1
    若某节点为n,则其父节点为n/2处
    """
    def __init__(self):
        self.heapList = [0]
        self.currentSize = 0

    #辅助函数,将某个位置的数据跟其父节点比大小,进行交换
    def percUp(self, i):
        while i // 2 > 0:
            if self.heapList[i] < self.heapList[i // 2]:
                self.heapList[i], self.heapList[i//2] =         self.heapList[i//2], self.heapList[i]
            i = i // 2

    #先添加新项到末尾,再执行辅助函数percUp将该值放到正确的位置
    def insert(self, k):
        self.heapList.append(k)
        self.currentSize = self.currentSize + 1
        self.percUp(self.currentSize)

    #删除最小项的辅助函数,将第i个节点(借助minChild函数)由上到下跟其左右子树比较,回到正确的地方
    def percDown(self, i):
        while (i*2) <= self.currentSize:
            mc = self.minChild(i)
            if self.heapList[i] > self.heapList[mc]:
                self.heapList[i], self.heapList[mc] = self.heapList[mc], self.heapList[i]
            i = mc

    #将第i项跟其左右子树比较,确定返回(左or右)值
    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

    #删除最小项,根据最小二叉堆的定义,根即为最小项,将最后一项赋值给根,再将新的根从上到下借助percDown函数回到正确的位置
    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

    #构建二叉堆,逐层构建
    def buildHeap(self, alist):
        i = len(alist) // 2
        self.currentSize = len(alist)
        self.heapList = [0] + alist[:]
        while i > 0:
            self.percDown(i)
            i = i - 1

#最小二叉堆测试
bh = BinaryHeap()
bh.buildHeap([9,5,6,2,3])

print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())

发表评论

评论列表,共 0 条评论

    暂无评论