← 中文资源

简体中文版本

堆排序建堆取顶(Rust)

原地建大顶堆后反复将最大值交换到末尾完成排序。

阅读英文原文

实现说明

堆排序建堆取顶(Rust)以函数 heapsort、sift_down为骨架。 文件的主干是一个循环——while root * 2 + 1 <= end。

使用要点

  • 调用方只需要 heapsort——其余都是内部实现。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 heapsort、sift_down。

签名一览:fn heapsort(arr: &mut [i32])

核心语句

if child + 1 <= end && arr[child] < arr[child + 1] { child += 1; }

代码示例

fn heapsort(arr: &mut [i32]) {
    let n = arr.len();
    fn sift_down(arr: &mut [i32], start: usize, end: usize) {
        let mut root = start;
        while root * 2 + 1 <= end {
            let mut child = root * 2 + 1;
            if child + 1 <= end && arr[child] < arr[child + 1] { child += 1; }
            if arr[root] < arr[child] { arr.swap(root, child); root = child; } else { return; }
        }
    }
    if n < 2 { return; }
    for i in (0..=(n - 2) / 2).rev() { sift_down(arr, i, n - 1); }
    for end in (1..n).rev() { arr.swap(0, end); sift_down(arr, 0, end - 1); }
}