rust-algorithms:8-堆排序

Rust
324
0
0
2022-11-10
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() {
        // 1. 最大的移到末尾 
        // 2. 重建堆(收缩)
        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)
    }
}