堆的 shift up
详解向最大堆末尾追加新元素后通过 shiftUp 沿父节点路径逐层上浮恢复堆序的过程、循环终止条件及 O(log n) 复杂度分析。
学完这一章,你能够
- 详解向最大堆末尾追加新元素后通过 shiftUp 沿父节点路径逐层上浮恢复堆序的过程、循环终止条件及 O(log n) 复杂度分析。
元素入堆与 shiftUp 上浮追踪
向最大堆插入新元素时,为保持完全二叉树形态,首先把新元素放置在底层数组的末尾空位 `count + 1`,随后自底向上修正可能被破坏的最大堆性质,这一上浮过程称为 `shiftUp`。以 10 元素最大堆 `[62, 41, 30, 28, 16, 22, 13, 19, 17, 15]` 为例,将新值 `52` 放入索引 `11` 后,其父节点位于索引 `11 // 2 = 5`(值为 `16`),因 `52 > 16` 违背最大堆定义,必须启动调整。
第一步交换索引 `11` 与索引 `5` 的元素,使 `52` 升至索引 `5`、`16` 降至索引 `11`。接着继续与新父节点索引 `5 // 2 = 2`(值为 `41`)比较,`52 > 41`,于是再交换索引 `5` 与索引 `2`。最后与根节点索引 `1`(值为 `62`)比较,满足 `52 <= 62`,上浮终止,整棵树重新满足最大堆约束。
核心实现逻辑与边界保护
在代码实现(如 `HeapShiftUp`)中,`insert(item)` 先断言 `count + 1 <= capacity` 防止越界,写入 `data[count + 1]` 并自增 `count`,再调用 `shiftUp(count)`。`shiftUp(k)` 使用 `while k > 1 and data[k // 2] < data[k]` 持续交换当前节点与父节点并令 `k //= 2`,单次插入最多沿树高比较和交换 O(log n) 次。来源示例代码压缩包在离线策略下不抓取,本地 Python 脚本已完整复现 `52` 上浮轨迹、50 元素批量入堆不变式及满容边界检验。
离线追踪最大堆插入 52 的 shiftUp 路径并校验批量入堆不变式
"""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()
- 在 CPython 3.12.14 离线脚本中验证插入 52 依次交换 (11,5) 与 (5,2)、50 个确定性元素入堆后全堆满足父大于等于子,以及升序入堆与容量溢出断言全部通过。
所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
当前源码 SHA256:9a120f6461c3ae629dc88fb689070f55fb533b6e6ea6d04d3a5c29229be4046a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。
ZIP SHA256:117d367f2ba478c07dc83f363b52d6d7360a2624b25a7731c7162de6fb1ea421
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `shiftUp(k)` 循环条件 `k > 1 and data[k // 2] < data[k]` 中,为什么必须先检查 `k > 1`?
展开参考解答
当 `k == 1` 时元素已到达根节点,此时 `k // 2 == 0` 指向未使用的 0 号哨兵槽位,不设 `k > 1` 守卫会导致访问空槽引发异常或越界比较。