class PriorityQueue:
def __init__(self):
self.heaplist = [(0, None)]
self.currentsize = 0
def perceedUp(self,index):
while index // 2 > 0:
if self.heaplist[index][0] < self.heaplist[index // 2][0]:
self.heaplist[index // 2], self.heaplist[index] = self.heaplist[index], self.heaplist[index // 2]
index = index // 2
def insert(self, item):
self.heaplist.append(item)
self.currentsize += 1
self.perceedUp(self.currentsize)
def perceedDown(self, index):
while index * 2 <= self.currentsize:
minChildIndex = self.minChild(index)
if self.heaplist[minChildIndex][0] < self.heaplist[index][0]:
self.heaplist[minChildIndex], self.heaplist[index] = self.heaplist[index], self.heaplist[minChildIndex]
index = minChildIndex
else:
break
def minChild(self, index):
if index * 2 + 1 > self.currentsize:
return index * 2
else:
if self.heaplist[index * 2][0] < self.heaplist[index * 2 + 1][0]:
return index * 2
else:
return index * 2 + 1
def delMin(self):
result = self.heaplist[1][1]
self.heaplist[1] = self.heaplist[self.currentsize]
self.currentsize -= 1
self.heaplist.pop()
self.perceedDown(1)
return result
def buildHeap(self, li):
i = len(li) // 2
self.heaplist = [(0, None)] + li
self.currentsize = len(li)
while i:
self.perceedDown(i)
i -= 1
if __name__ == '__main__':
pq = PriorityQueue()
pq.insert((2,'zhangsan'))
pq.insert((5, 'lisi'))
pq.insert((1, 'wangwu'))
pq.insert((6, 'aaa'))
pq.insert((9, 'bbb'))
print(pq.delMin())
print(pq.delMin())
print(pq.delMin())
输出:
wangwu
zhangsan
lisi