# 插入操作 (Insert)
def push(heap, val):
heap.append(val)
bubble_up(len(heap) - 1)
# 上浮调整 (Bubble Up)
def bubble_up(idx):
while idx > 0:
p_idx = (idx - 1) // 2
if heap[idx] < heap[p_idx]:
swap(idx, p_idx)
idx = p_idx
else: break
# 取出操作 (Extract)
def pop(heap):
if not heap: return None
min_val = heap[0]
heap[0] = heap.pop()
bubble_down(0)
return min_val
# 下沉调整 (Bubble Down)
def bubble_down(idx):
while True:
l, r = 2*idx+1, 2*idx+2
small = idx
if l < len and h[l] < h[small]:
small = l
if r < len and h[r] < h[small]:
small = r
if small != idx:
swap(idx, small)
idx = small
else: break