蓝色天空网mbsky.com · 知识 · 实践 · 创造数据结构与算法 · 本地阅读预览
教程 / 计算机基础 / 数据结构与算法

堆的 shift down

详解从最大堆取出堆顶元素后将末尾元素补位至根部、反复与较大子节点交换执行 shiftDown 下沉恢复堆序的过程与实现细节。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

堆顶出堆与 shiftDown 下沉追踪

从最大堆取出元素时只能移除优先级最高的堆顶根节点 `data[1]`。为了在移除后继续维持完全二叉树结构,第一步将数组末尾元素 `data[count]` 交换至根节点位置并将 `count` 减 1。以堆顶 `62` 出堆为例,原末尾元素 `16` 被移至索引 `1`,此时根节点小于其子节点,破坏了最大堆定义,需要通过 `shiftDown(1)` 逐步下沉修复。

下沉过程中,节点 `16` 在索引 `1` 处比较左孩子 `52`(索引 `2`)与右孩子 `30`(索引 `3`),选出更大者 `52` 与之交换;抵达索引 `2` 后,再比较其左右孩子 `28`(索引 `4`)与 `41`(索引 `5`),因 `41` 更大且 `16 < 41`,继续与 `41` 交换至索引 `5`;最后仅剩左孩子 `15`(索引 `10`),满足 `16 >= 15`,停止交换并完成 `shiftDown`。

extractMax 实现细节与单调出堆验证

在完整实现 `HeapShiftDown` 中,`extractMax()` 先断言 `count > 0`,保存 `data[1]`、交换索引 `1` 与 `count`、令 `count -= 1`,然后调用 `shiftDown(1)`。循环条件 `2 * k <= count` 确保当前节点至少存在左孩子,若 `j + 1 <= count` 且右孩子更大则将目标下标 `j` 切换至右孩子;一旦 `data[k] >= data[j]` 立即跳出。连续对 n 个元素执行 `extractMax()` 将稳定输出非递增有序序列,离线 Python 脚本已完整复现 `62` 出堆轨迹、100 元素降序校验及空堆断言边界。

离线追踪取出 62 后的 shiftDown 下沉路径并验证 100 元素连续出堆有序性

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 在 CPython 3.12.14 离线脚本中确认提取 62 后 16 依次与 52、41 交换并在 15 处停止,100 元素连续 extractMax 产出严格降序序列且每步保持最大堆不变式。
离线追踪取出 62 后的 shiftDown 下沉路径并验证 100 元素连续出堆有序性

所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。

当前源码 SHA256:f4794f6bdccca8a8f32614776ebeb34dca1baf01589efbf26529e91463a7e5b8

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载堆的 shift down实验

所需环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。

ZIP SHA256:ed9ca6995e610e585b806dcdd55ebebf16bb30eca9c2cba984cad5f34201e7ed

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 `shiftDown(k)` 中,为什么每次必须先在左右孩子中挑出较大的那一个再与父节点比较?

展开参考解答

若将较小的孩子提升到父节点位置,该新父节点仍会小于其另一个兄弟节点,导致最大堆性质依然被破坏;只有提升较大孩子,才能保证新父节点同时大于等于左右子树根。

规范与官方依据