python实现最大堆
堆是利用的完全二叉树的性质,并且利用数组来实现的一种特殊数据结构
堆的应用场景
- 堆排序
- 优先级队列
- 高性能定时器
- 取中位数
实现堆的关键
- 堆的维持(从上到下,从下到上)
- 压堆
- 获得堆顶
具体实现代码
class myHeap(object):
'''
max heap
'''
def __init__(self):
self.heap = []
def add(self,item):
self.heap.append(item)
self.heapity(len(self.heap)-1)
def show(self):
print(self.heap)
def heapity(self,index):
'''
this funtion using from button start target heap list heapity
'''
ii = (index-1) // 2
if index > 0 and ii >= 0 and self.heap[index] > self.heap[ii]:
self.heap[index],self.heap[ii] = self.heap[ii],self.heap[index]
self.heapity(ii)
def heapity_up(self,index):
'''
heapity heap is from up to button
'''
#因为二叉树,所以有子节点需要判断节点就只有len(heap)//2个
if index >= len(self.heap) // 2:
return
ll,rr = index*2+1,index*2+2
#print(f"index:{index},ll:{ll},rr:{rr},len:{len(self.heap)}")
if rr < len(self.heap) and self.heap[rr] >= self.heap[ll] and self.heap[rr] >= self.heap[index]:
self.heap[index],self.heap[rr] = self.heap[rr],self.heap[index]
self.heapity_up(rr)
elif self.heap[ll] >= self.heap[index]:
self.heap[index],self.heap[ll] = self.heap[ll],self.heap[index]
self.heapity_up(ll)
def getMax(self):
'''
get max value from heap
'''
if len(self.heap) <= 0:
print("[error]:heap is emtpy,not can get max value,sorry!!!")
return
elif len(self.heap) <= 2:
rel = self.heap.pop(0)
print(f"max:{rel}")
return rel
else:
rel = self.heap[0]
self.heap[0] = self.heap.pop() #因为>2所以pop一个元素之后,肯定还有>2元素存在,需要排列了
self.heapity_up(0)
print(f"[max]:{rel}")
return rel
if __name__ == "__main__":
a = myHeap()
a.show()
a.add(5)
a.show()
a.add(7)
a.show()
a.add(3)
a.show()
a.add(4)
a.show()
a.add(10)
a.show()
a.add(11)
a.show()
a.add(6)
a.show()
print("-"*50)
a.getMax()
a.getMax()
a.getMax()
a.getMax()
a.getMax()
a.getMax()
a.getMax()