python数据结构_大顶堆和小顶堆
2020-12-18 13:36
标签:== build 代码实现 复杂 end list() 实现 main 代码 相关介绍可参看:北京大学空地学院数据结构与算法 第六章 6.8.2.2 小节 python数据结构_大顶堆和小顶堆 标签:== build 代码实现 复杂 end list() 实现 main 代码 原文地址:https://www.cnblogs.com/yezigege/p/13386408.html大顶堆和小顶堆
代码实现如下
class Heap:
"""二叉堆的实现 小顶堆"""
def __init__(self):
self.heapList = [0] # 默认一个 0 做占位,使得根节点的索引在 1 上
self.currentSize = 0 # 最大节点的索引位置
def perUp(self, i):
"""将小节点逐步上升"""
while i // 2 > 0:
if self.heapList[i] self.currentSize: # 右子节点超出节点数量
return i * 2
else:
if self.heapList[i * 2] self.heapList[mc]:
self.heapList[i], self.heapList[mc] = self.heapList[mc], self.heapList[i]
i = mc
def delMin(self):
"""删除小节点"""
retval = self.heapList[1] # 删除索引位置为 1 的节点
self.heapList[1] = self.heapList[self.currentSize]
self.heapList.pop()
self.currentSize -= 1
self.perDown(1)
return retval
def buildHeap(self, alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList += alist[:]
while i > 0:
self.perDown(i)
i -= 1
class HeapList(object):
"""大顶推"""
def __init__(self):
self.heaplist = [0]
self.size = 0
def buildHeap(self, alist):
i = len(alist) // 2
self.size = len(alist)
self.heaplist += alist[:]
while i > 0:
self.percDown(i)
i -= 1
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 //= 2
def insert(self, k):
self.heaplist.append(k)
self.size += 1
self.percUp(self.size)
def maxChild(self, i):
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):
while i * 2
文章标题:python数据结构_大顶堆和小顶堆
文章链接:http://soscw.com/index.php/essay/37100.html