"""Offline algorithm verification lab for Chapter 22 (heap-shift-up)."""
import json
VERSION = "CPython 3.12.14 offline DSA verifier (heap-shift-up)"
class MaxHeapShiftUp:
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 insert(self, item) -> list:
assert self.count + 1 <= self.capacity, "Heap overflow"
self.data[self.count + 1] = item
self.count += 1
return self._shift_up(self.count)
def _shift_up(self, k: int) -> list:
swaps = []
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]
swaps.append([k, k // 2])
k //= 2
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_up_trace_insert_52():
heap = MaxHeapShiftUp(20)
# Initial 10-element max heap matching the textbook walk-through
initial = [62, 41, 30, 28, 16, 22, 13, 19, 17, 15]
for idx, val in enumerate(initial, start=1):
heap.data[idx] = val
heap.count = len(initial)
assert heap.is_valid_max_heap()
swaps = heap.insert(52)
expected = {
"swap_pairs": [[11, 5], [5, 2]],
"final_array": [62, 52, 30, 28, 41, 22, 13, 19, 17, 15, 16],
"root": 62,
"index_2_value": 52,
"index_5_value": 41,
"index_11_value": 16,
"valid_heap": True,
}
actual = {
"swap_pairs": swaps,
"final_array": heap.snapshot(),
"root": heap.data[1],
"index_2_value": heap.data[2],
"index_5_value": heap.data[5],
"index_11_value": heap.data[11],
"valid_heap": heap.is_valid_max_heap(),
}
return {
"name": "shift_up_trace_insert_52",
"summary": "逐步追踪向 10 元素最大堆末尾插入 52 时的 shiftUp 交换路径:(11,5)->(5,2) 并止步于根节点 62",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_max_heap_bulk_insert_invariant():
heap = MaxHeapShiftUp(100)
items = [(i * 29 + 17) % 100 for i in range(50)]
for x in items:
heap.insert(x)
expected = {
"size": 50,
"is_empty": False,
"root_equals_max": True,
"max_value": max(items),
"valid_heap": True,
}
actual = {
"size": heap.size(),
"is_empty": heap.is_empty(),
"root_equals_max": heap.data[1] == max(items),
"max_value": heap.data[1],
"valid_heap": heap.is_valid_max_heap(),
}
return {
"name": "max_heap_bulk_insert_invariant",
"summary": "向容量 100 的最大堆连续插入 50 个确定性整数,校验元素计数、堆顶最大值与全堆父子序不变式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_shift_up_boundary_conditions():
heap = MaxHeapShiftUp(8)
# Strictly ascending insertions force each new key to bubble all the way to root
swap_counts = [len(heap.insert(v)) for v in [10, 20, 30, 40, 40, 5, 50, 50]]
overflow_raised = False
try:
heap.insert(99)
except AssertionError:
overflow_raised = True
expected = {
"swap_counts": [0, 1, 1, 2, 1, 0, 2, 2],
"root": 50,
"size": 8,
"valid_heap": True,
"overflow_guarded": True,
}
actual = {
"swap_counts": swap_counts,
"root": heap.data[1],
"size": heap.size(),
"valid_heap": heap.is_valid_max_heap(),
"overflow_guarded": overflow_raised,
}
return {
"name": "shift_up_boundary_conditions",
"summary": "验证升序插入、重复键值与满容量断言保护在 shiftUp 过程中的边界行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_shift_up_trace_insert_52(),
case_max_heap_bulk_insert_invariant(),
case_shift_up_boundary_conditions(),
]
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-up-lab/explore-heap-shift-up.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-heap-shift-up.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2668.zip