蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-heap-storage.py
explore-heap-storage.py220 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/data-structures-heap-storage-lab/explore-heap-storage.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-heap-storage.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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