堆
是完全二叉树,应用:优先队列
最大/最小堆
从根节点开始到任一叶节点的路径是有序的(从大到小/从小到大)
基本操作
创建空堆
是否已满
插入元素
是否为空
返回最高优先级元素
def insert_data(heap, x):
if len(heap.data) > heap.maxsize: # 判断堆是否已满
print('Full')
else:
heap.size += 1
heap.data.append(x) # 先放在数组的最后
i = heap.size
while i:
if x > heap.data[i//2]: # 比较插入点与父节点的大小,比父节点大即与父节点交换
heap.data[i] = heap.data[i//2]
heap.data[i//2] = x
i //= 2
else:
break
return heap
def delete_data(heap):
if len(heap.data) == 1: # 判断堆是否已空
print('Empty')
else:
data = heap.data[1] # 根节点即最大值
temp = heap.data[heap.size] # 把最后一个元素提出
heap.data.pop()
heap.size -= 1
parent = 1
while parent*2 <= heap.size:
child = parent * 2
if child != heap.size and heap.data[child] < heap.data[child+1]:
child += 1
if temp > heap.data[child]:
break
else:
heap.data[parent] = heap.data[child]
parent = child
heap.data[parent] = temp
return data
class Heap:
def __init__(self):
self.size = 0 # 当前容量
self.maxsize = 0 # 堆的最大容量
self.data = [0] # 存储堆元素的数组
max_heap = Heap()
max_heap.maxsize = 10
max_heap.data[0] = 10000 # 放一个比所有元素都大的值,做哨兵