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

离线验证 O(n) Heapify 自底向上建堆、100 元素堆排序与交换次数实测对比

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-heap-sort.py
explore-heap-sort.py168 行
"""Offline algorithm verification lab for Chapter 24 (heap-sort / Heapify)."""
import json

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


class HeapifyMaxHeap:
    def __init__(self, arr: list):
        n = len(arr)
        self.data = [None] * (n + 1)
        self.capacity = n
        for i in range(n):
            self.data[i + 1] = arr[i]
        self.count = n
        self.build_swaps = 0
        self.build_comparisons = 0
        self.step_snapshots = {}
        # Start from the first non-leaf node: count // 2 down to 1
        for i in range(self.count // 2, 0, -1):
            self._shift_down(i, count_build=True)
            self.step_snapshots[i] = self.data[1 : self.count + 1]

    def size(self) -> int:
        return self.count

    def is_empty(self) -> bool:
        return self.count == 0

    def extract_max(self):
        assert self.count > 0
        ret = self.data[1]
        self.data[1], self.data[self.count] = self.data[self.count], self.data[1]
        self.count -= 1
        self._shift_down(1, count_build=False)
        return ret

    def _shift_down(self, k: int, count_build: bool = False):
        while 2 * k <= self.count:
            j = 2 * k
            if j + 1 <= self.count:
                if count_build:
                    self.build_comparisons += 1
                if self.data[j + 1] > self.data[j]:
                    j += 1
            if count_build:
                self.build_comparisons += 1
            if self.data[k] >= self.data[j]:
                break
            self.data[k], self.data[j] = self.data[j], self.data[k]
            if count_build:
                self.build_swaps += 1
            k = j

    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_heapify_bottom_up_trace():
    # 10-element input where index 5 (first non-leaf = 10//2) holds 22 and child 10 holds 62
    arr = [15, 17, 19, 13, 22, 16, 28, 30, 41, 62]
    heap = HeapifyMaxHeap(arr)
    expected = {
        "first_non_leaf": 5,
        "after_i5_idx5_and_idx10": [62, 22],
        "after_i1_root": 62,
        "final_heap": [62, 41, 28, 30, 22, 16, 19, 15, 13, 17],
        "valid_heap": True,
    }
    actual = {
        "first_non_leaf": len(arr) // 2,
        "after_i5_idx5_and_idx10": [heap.step_snapshots[5][4], heap.step_snapshots[5][9]],
        "after_i1_root": heap.step_snapshots[1][0],
        "final_heap": heap.step_snapshots[1],
        "valid_heap": heap.is_valid_max_heap(),
    }
    return {
        "name": "heapify_bottom_up_trace",
        "summary": "追踪 10 元素数组从第一个非叶子节点 n//2=5 倒序执行 shiftDown 至 1 的 Heapify 建堆全过程",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_heapify_extract_sort():
    source = [(i * 971 + 53) % 100000 for i in range(100)]
    heap = HeapifyMaxHeap(source)
    desc = [heap.extract_max() for _ in range(len(source))]
    asc = list(reversed(desc))
    expected = {
        "count": 100,
        "desc_correct": True,
        "asc_correct": True,
        "heap_empty": True,
    }
    actual = {
        "count": len(desc),
        "desc_correct": desc == sorted(source, reverse=True),
        "asc_correct": asc == sorted(source),
        "heap_empty": heap.is_empty(),
    }
    return {
        "name": "heapify_extract_sort",
        "summary": "通过 Heapify 构造最大堆并连续 extractMax 完成 100 个确定性整数的堆排序校验",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_heapify_vs_insert_operation_count():
    # Worst-case ascending input of size 255: insert(shiftUp) is O(n log n), Heapify is O(n)
    n = 255
    arr = list(range(1, n + 1))

    # Build via Heapify
    h = HeapifyMaxHeap(arr)
    heapify_swaps = h.build_swaps

    # Build via repeated shiftUp
    data = [None]
    insert_swaps = 0
    for x in arr:
        data.append(x)
        k = len(data) - 1
        while k > 1 and data[k // 2] < data[k]:
            data[k // 2], data[k] = data[k], data[k // 2]
            k //= 2
            insert_swaps += 1

    expected = {
        "heapify_valid": True,
        "heapify_swaps_below_n": True,
        "heapify_much_fewer_swaps_than_insert": True,
        "heapify_swaps": 247,
        "insert_swaps": 1538,
    }
    actual = {
        "heapify_valid": h.is_valid_max_heap(),
        "heapify_swaps_below_n": heapify_swaps < n,
        "heapify_much_fewer_swaps_than_insert": heapify_swaps * 5 < insert_swaps,
        "heapify_swaps": heapify_swaps,
        "insert_swaps": insert_swaps,
    }
    return {
        "name": "heapify_vs_insert_operation_count",
        "summary": "在 255 个升序元素上实测 O(n) Heapify 与 O(n log n) 逐个 shiftUp 建堆的交换次数差距",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_heapify_bottom_up_trace(),
        case_heapify_extract_sort(),
        case_heapify_vs_insert_operation_count(),
    ]
    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-sort-lab/explore-heap-sort.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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