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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.