rust-algorithms:8-堆排序


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)
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!