"""Offline algorithm verification lab for Chapter 23 (heap-shift-down)."""
import json
VERSION = "CPython 3.12.14 offline DSA verifier (heap-shift-down)"
class MaxHeapShiftDown:
def __init__(self, capacity: int):
self.data = [None] * (capacity + 1)
self.count = 0
self.capacity = capacity
def size(self) -> int:
return self.count
def is_empty(self) -> bool:
return self.count == 0
def get_max(self):
assert self.count > 0, "Heap is empty"
return self.data[1]
def insert(self, item):
assert self.count + 1 <= self.capacity, "Heap overflow"
self.data[self.count + 1] = item
self.count += 1
self._shift_up(self.count)
def extract_max_with_trace(self):
assert self.count > 0, "Heap is empty"
ret = self.data[1]
self.data[1], self.data[self.count] = self.data[self.count], self.data[1]
self.count -= 1
swaps = self._shift_down(1)
return ret, swaps
def extract_max(self):
ret, _ = self.extract_max_with_trace()
return ret
def _shift_up(self, k: int):
while k > 1 and self.data[k // 2] < self.data[k]:
self.data[k], self.data[k // 2] = self.data[k // 2], self.data[k]
k //= 2
def _shift_down(self, k: int) -> list:
swaps = []
while 2 * k <= self.count:
j = 2 * k
if j + 1 <= self.count and self.data[j + 1] > self.data[j]:
j += 1
if self.data[k] >= self.data[j]:
break
self.data[k], self.data[j] = self.data[j], self.data[k]
swaps.append([k, j])
k = j
return swaps
def snapshot(self) -> list:
return self.data[1 : self.count + 1]
def is_valid_max_heap(self) -> bool:
for i in range(2, self.count + 1):
if self.data[i // 2] < self.data[i]:
return False
return True
def case_shift_down_trace_extract_62():
heap = MaxHeapShiftDown(20)
initial = [62, 52, 30, 28, 41, 22, 13, 19, 17, 15, 16]
for idx, val in enumerate(initial, start=1):
heap.data[idx] = val
heap.count = len(initial)
extracted, swaps = heap.extract_max_with_trace()
expected = {
"extracted": 62,
"swap_pairs": [[1, 2], [2, 5]],
"final_array": [52, 41, 30, 28, 16, 22, 13, 19, 17, 15],
"new_max": 52,
"valid_heap": True,
}
actual = {
"extracted": extracted,
"swap_pairs": swaps,
"final_array": heap.snapshot(),
"new_max": heap.get_max(),
"valid_heap": heap.is_valid_max_heap(),
}
return {
"name": "shift_down_trace_extract_62",
"summary": "逐步追踪取出堆顶 62 后将末尾 16 移至根部并执行 shiftDown:(1,2)换52、(2,5)换41、与15比较后停止",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_extract_max_descending_order():
heap = MaxHeapShiftDown(100)
source = [(i * 43 + 19) % 100 for i in range(100)]
for v in source:
heap.insert(v)
peek_before = heap.get_max()
extracted = []
invariants_all_ok = True
for _ in range(100):
extracted.append(heap.extract_max())
if not heap.is_valid_max_heap():
invariants_all_ok = False
is_descending = all(extracted[i - 1] >= extracted[i] for i in range(1, len(extracted)))
expected = {
"peek_equals_max": True,
"is_descending": True,
"matches_sorted_desc": True,
"invariants_all_ok": True,
"empty_after_all": True,
}
actual = {
"peek_equals_max": peek_before == max(source),
"is_descending": is_descending,
"matches_sorted_desc": extracted == sorted(source, reverse=True),
"invariants_all_ok": invariants_all_ok,
"empty_after_all": heap.is_empty(),
}
return {
"name": "extract_max_descending_order",
"summary": "对 100 个确定性元素反复执行 extractMax,验证每次下沉后堆不变式成立且输出严格非递增序列",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_shift_down_edge_cases():
h1 = MaxHeapShiftDown(4)
h1.insert(7)
single_out = h1.extract_max()
empty_guarded = False
try:
h1.extract_max()
except AssertionError:
empty_guarded = True
h2 = MaxHeapShiftDown(5)
for x in [20, 20, 20, 10, 10]:
h2.insert(x)
out2 = [h2.extract_max() for _ in range(5)]
expected = {
"single_out": 7,
"single_now_empty": True,
"empty_guarded": True,
"equal_children_out": [20, 20, 20, 10, 10],
}
actual = {
"single_out": single_out,
"single_now_empty": h1.is_empty(),
"empty_guarded": empty_guarded,
"equal_children_out": out2,
}
return {
"name": "shift_down_edge_cases",
"summary": "验证单元素出堆、空堆提取断言保护及左右子节点相等时的 shiftDown 边界行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_shift_down_trace_extract_62(),
case_extract_max_descending_order(),
case_shift_down_edge_cases(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
入口文件:projects/data-structures-heap-shift-down-lab/explore-heap-shift-down.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-heap-shift-down.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2667.zip