蓝色天空.知识 · 实践 · 创造
我的收藏
数据结构与算法 教程目录 44章
数据结构与算法 / LEARN BY DOING

堆的基本存储

系统介绍二叉堆的完全二叉树结构约束、堆序性质、优先队列场景下的复杂度优势,以及基于 1-based 数组的父子节点下标映射公式与基础容器骨架。

学完这一章,你能够

  • 系统介绍二叉堆的完全二叉树结构约束、堆序性质、优先队列场景下的复杂度优势,以及基于 1-based 数组的父子节点下标映射公式与基础容器骨架。

概念定义与优先队列适用场景

堆(Heap)是计算机科学中一类特殊的树形抽象数据结构,在工程实现中通常表现为可视作完全二叉树的数组对象。一个合法的二叉堆必须同时满足两项约束:其一为堆序性,任意节点的值总是不大于其父节点(最大堆)或总是不小于其父节点(最小堆);其二为结构性,整体始终保持完全二叉树形态。

依托完全二叉树的高度对数上界,堆维护动态数据集合时的单次核心操作通常介于 O(1) 到 O(log n) 之间,除用于系统内存或对象的动态调度外,最典型的应用是实现优先队列。若改用普通无序数组或顺序数组实现优先队列,连续执行 n 次入队与出队的最坏总开销都会退化至 O(n^2),而二叉堆可将入队与出队稳定控制在 O(log n)(下表同步修正了原参考表“堆出队”一栏的笔误 `O(log)` 为 `O(log n)`)。

完全二叉树数组存储与下标映射

深度为 k 的完全二叉树要求第 1 层至第 k-1 层的节点全部填满,第 k 层的节点连续紧靠最左侧排列。当根节点取全堆最大值时称为最大堆(Max-Heap)。

正因为完全二叉树不存在中间空洞,可以按层序从上到下、从左到右紧凑存入一维数组。若跳过下标 0、从索引 `1` 开始存放根节点,则任意索引 `i`(`1 <= i <= count`)对应的父节点与左右孩子索引满足简洁的整数运算规律:`parent(i) = i // 2`、`left(i) = 2 * i`、`right(i) = 2 * i + 1`。

基础最大堆容器设计与本地验证

在面向对象骨架 `MaxHeap` 中,构造函数按 `capacity + 1` 分配内部数组(预留 0 号哨兵槽位,实际可存 `capacity` 个元素),并维护当前元素计数 `count` 以及 `size()`、`isEmpty()` 两个 O(1) 查询方法。来源页附带的示例压缩包在离线策略下不发起抓取,改由本地 Python 实验脚本完整验证 1-based 下标映射、容量分配与三种优先队列实现的操作步数对比。

普通数组、顺序数组与二叉堆实现优先队列的时间复杂度对比

数据结构入队(Enqueue)出队(Dequeue)
普通数组O(1)O(n)
顺序数组O(n)O(1)
二叉堆(Heap)O(log n)O(log n)

离线校验 1-based 二叉堆下标映射、MaxHeap 基础骨架与优先队列复杂度对比

含完整源码 · 220 行
展开查看收起
python
"""Offline algorithm verification lab for Chapter 21 (heap-storage)."""
import json

VERSION = "CPython 3.12.14 offline DSA verifier (heap-storage)"


class MaxHeapBase:
    """1-based array storage container for a binary max-heap."""

    def __init__(self, capacity: int):
        if capacity < 0:
            raise ValueError("capacity must be non-negative")
        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

    @staticmethod
    def parent(i: int) -> int:
        return i // 2

    @staticmethod
    def left_child(i: int) -> int:
        return 2 * i

    @staticmethod
    def right_child(i: int) -> int:
        return 2 * i + 1


def case_complete_binary_tree_index_mapping():
    # 1-based complete binary tree array of 10 nodes satisfying max-heap order
    arr = [None, 62, 41, 30, 28, 16, 22, 13, 19, 17, 15]
    n = len(arr) - 1
    relations = {}
    heap_valid = True
    for i in range(1, n + 1):
        p = MaxHeapBase.parent(i) if i > 1 else None
        l = MaxHeapBase.left_child(i) if MaxHeapBase.left_child(i) <= n else None
        r = MaxHeapBase.right_child(i) if MaxHeapBase.right_child(i) <= n else None
        if p is not None and arr[p] < arr[i]:
            heap_valid = False
        relations[i] = {"val": arr[i], "parent": p, "left": l, "right": r}

    expected = {
        "node_1": {"val": 62, "parent": None, "left": 2, "right": 3},
        "node_5": {"val": 16, "parent": 2, "left": 10, "right": None},
        "node_10": {"val": 15, "parent": 5, "left": None, "right": None},
        "heap_valid": True,
        "depth": 4,
    }
    depth = n.bit_length()
    actual = {
        "node_1": relations[1],
        "node_5": relations[5],
        "node_10": relations[10],
        "heap_valid": heap_valid,
        "depth": depth,
    }
    return {
        "name": "complete_binary_tree_index_mapping",
        "summary": "验证 1-based 完全二叉树数组中 parent(i)=i//2、left=2i、right=2i+1 索引映射及最大堆性质",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_max_heap_container_lifecycle():
    heap = MaxHeapBase(100)
    expected = {
        "initial_size": 0,
        "initial_empty": True,
        "allocated_slots": 101,
        "capacity": 100,
        "slot_zero_unused": True,
    }
    actual = {
        "initial_size": heap.size(),
        "initial_empty": heap.is_empty(),
        "allocated_slots": len(heap.data),
        "capacity": heap.capacity,
        "slot_zero_unused": heap.data[0] is None,
    }
    return {
        "name": "max_heap_container_lifecycle",
        "summary": "验证容量为 100 的 MaxHeap 基础容器分配 capacity+1 槽位及 size()/is_empty() 初始状态",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_priority_queue_complexity_comparison():
    # Empirical step counts for enqueue + dequeue of max on 64 elements
    values = [(i * 37 + 13) % 100 for i in range(64)]

    # 1. Unsorted array: O(1) enqueue, O(n) dequeue
    unsorted = []
    unsorted_enq_ops = 0
    unsorted_deq_ops = 0
    for v in values:
        unsorted.append(v)
        unsorted_enq_ops += 1
    out_unsorted = []
    while unsorted:
        max_idx = 0
        for i in range(1, len(unsorted)):
            unsorted_deq_ops += 1
            if unsorted[i] > unsorted[max_idx]:
                max_idx = i
        out_unsorted.append(unsorted.pop(max_idx))

    # 2. Sorted array (ascending): O(n) enqueue, O(1) dequeue from tail
    ordered = []
    ordered_enq_ops = 0
    ordered_deq_ops = 0
    for v in values:
        pos = len(ordered)
        ordered.append(v)
        while pos > 0 and ordered[pos - 1] > v:
            ordered[pos] = ordered[pos - 1]
            pos -= 1
            ordered_enq_ops += 1
        ordered[pos] = v
    out_ordered = []
    while ordered:
        out_ordered.append(ordered.pop())
        ordered_deq_ops += 1

    # 3. Binary max-heap: O(log n) enqueue, O(log n) dequeue
    heap = [None]
    heap_enq_ops = 0
    heap_deq_ops = 0
    for v in values:
        heap.append(v)
        k = len(heap) - 1
        while k > 1 and heap[k // 2] < heap[k]:
            heap[k // 2], heap[k] = heap[k], heap[k // 2]
            k //= 2
            heap_enq_ops += 1
    out_heap = []
    while len(heap) > 1:
        out_heap.append(heap[1])
        last = heap.pop()
        if len(heap) > 1:
            heap[1] = last
            k = 1
            n = len(heap) - 1
            while 2 * k <= n:
                j = 2 * k
                if j + 1 <= n and heap[j + 1] > heap[j]:
                    j += 1
                heap_deq_ops += 1
                if heap[k] >= heap[j]:
                    break
                heap[k], heap[j] = heap[j], heap[k]
                k = j

    expected = {
        "outputs_identical": True,
        "unsorted_total_greater_than_heap": True,
        "ordered_total_greater_than_heap": True,
        "unsorted_enq_is_linear_n": True,
        "ordered_deq_is_linear_n": True,
    }
    actual = {
        "outputs_identical": (out_unsorted == out_ordered == out_heap),
        "unsorted_total_greater_than_heap": (unsorted_enq_ops + unsorted_deq_ops) > (heap_enq_ops + heap_deq_ops),
        "ordered_total_greater_than_heap": (ordered_enq_ops + ordered_deq_ops) > (heap_enq_ops + heap_deq_ops),
        "unsorted_enq_is_linear_n": unsorted_enq_ops == 64,
        "ordered_deq_is_linear_n": ordered_deq_ops == 64,
    }
    return {
        "name": "priority_queue_complexity_comparison",
        "summary": "对比普通数组、顺序数组与二叉堆在 64 元素优先队列入队/出队上的输出一致性与操作开销",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_source_archive_offline_audit():
    attachment = {
        "requested_online": False,
        "policy": "inherited_origin_hold",
        "replaced_by_local_lab": True,
    }
    expected = {"offline_only": True, "local_lab_available": True}
    actual = {
        "offline_only": not attachment["requested_online"],
        "local_lab_available": attachment["replaced_by_local_lab"],
    }
    return {
        "name": "source_archive_offline_audit",
        "summary": "确认来源示例代码压缩包在离线策略下未发起网络抓取,由本地实验脚本提供等效可运行验证",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_complete_binary_tree_index_mapping(),
        case_max_heap_container_lifecycle(),
        case_priority_queue_complexity_comparison(),
        case_source_archive_offline_audit(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
在 CPython 3.12.14 离线脚本中确认 10 节点最大堆父子索引关系、容量 100 容器分配 101 槽位、64 元素三种优先队列输出一致且二叉堆总操作数显著低于数组实现。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a2641.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2671.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

父节点为 `5 // 2 = 2`,左孩子为 `2 * 5 = 10`(有效),右孩子 `2 * 5 + 1 = 11 > 10` 不存在。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习