pub fn heap_sort<T: PartialOrd>(arr: &mut [T]) {
let len = arr.len();
for index in (0..len / 2).rev() {
heapify(arr, index, len);
}
for index in (1..len).rev() {
arr.swap(0, index);
heapify(arr, 0, index);
}
}
fn heapify<T: PartialOrd>(arr: &mut [T], root: usize, end: usize) {
let mut largest_index = root;
let left_index = 2 * root + 1;
if left_index < end && arr[left_index] > arr[largest_index] {
largest_index = left_index;
}
let right_index = left_index + 1;
if right_index < end && arr[right_index] > arr[largest_index] {
largest_index = right_index;
}
if largest_index != root {
arr.swap(largest_index, root);
heapify(arr, largest_index, end)
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結