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

基础堆排序

系统讲解利用完全二叉树首个非叶子节点 n//2 倒序执行 shiftDown 的 O(n) Heapify 建堆过程,并结合连续 extractMax 完成基础堆排序。

学完这一章,你能够

  • 系统讲解利用完全二叉树首个非叶子节点 n//2 倒序执行 shiftDown 的 O(n) Heapify 建堆过程,并结合连续 extractMax 完成基础堆排序。

堆排序概念与 O(n) Heapify 建堆优势

堆排序(Heapsort)是借助二叉堆这一近似完全二叉树数据结构设计的经典比较排序算法,核心依托“父节点键值总是不小于(最大堆)或不大于(最小堆)子节点键值”的堆序性质来反复提取极值。

如果将 n 个待排序元素逐一调用 `insert` 经由 `shiftUp` 插入空堆,建堆阶段需要 O(n log n) 时间。采用自底向上的 `Heapify` 算法直接把整个无序数组视作完全二叉树并原地调整为堆,可将建堆复杂度严格优化至 O(n)(因为约一半节点是无需下沉的叶子,越靠近底层下沉步数越少,几何级数求和上界线性于 n)。

从首个非叶子节点倒序 shiftDown 的全过程

对于 1-based 存储的 n 节点完全二叉树,所有下标大于 `n // 2` 的节点均为叶子节点,天然满足单节点子堆定义,因此第一个非叶子节点的索引恰好为 `n // 2`。以 10 元素数组为例,`10 // 2 = 5`,算法从索引 `5` 开始倒序逐一作为子堆根执行 `shiftDown`;当索引 `5` 存放 `22`、其左孩子索引 `10` 存放 `62` 时,第一步交换 `22` 与 `62`。

随后依次对索引 `4`、索引 `3`、索引 `2` 执行 `shiftDown`,保证每处理完一个索引,其对应子树都成为合法最大堆;最后对根节点索引 `1` 执行 `shiftDown`,整棵完全二叉树即完成最大堆构造。

Heapify 构造与出堆排序实测

在 `Heapify` 构造实现中,先将输入数组拷贝至 1-based `data[1..n]`,再用 `for i in range(count // 2, 0, -1): shiftDown(i)` 线性建堆,随后循环调用 n 次 `extractMax()` 即可得到有序输出(若逆序回填则得升序)。本地 Python 实验脚本不仅验证了 10 元素自底向上建堆与 100 元素堆排序,还在 255 个升序元素上实测出 Heapify 仅需 247 次交换,远低于逐个 `shiftUp` 插入的 1538 次交换。

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

含完整源码 · 168 行
展开查看收起
python
"""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()
在 CPython 3.12.14 离线脚本中确认 10 元素数组自索引 5 倒序建堆成功、100 元素出堆严格有序,且 255 升序元素建堆交换次数 247 显著低于逐个插入的 1538。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Heapify 中占总数一半的叶子节点执行 0 次下沉,倒数第二层最多下沉 1 层,越往高层节点数按 2 的幂衰减,总步数受限于 `n * sum(h / 2^(h+1)) <= n`;而逐个 `insert` 时最底层的 `n/2` 个节点都可能需要上浮整棵树高 `log n` 层,总步数达到 `Theta(n log n)`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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