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); }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.