Heapsort Build And Extract Max (Rust)

Sort a Rust slice by building a max heap in place then repeatedly extracting the maximum to the end.

RustData Integrity

Code

rustsnippet
14 lines
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); }
}

How it works

Structurally, expect the functions heapsort and sift_down and nothing else.

Iteration happens inside while root * 2 + 1 <= end — everything outside it runs once.

Putting it to use

The primary signature is fn heapsort(arr: &mut [i32])

heapsort is what another module would consume; nothing else here is load-bearing for callers.

Core lines

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

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `heapsort`, `sift_down` at load time.