rust-algorithms:4-鸡尾酒排序

Rust
283
0
0
2022-11-10
pub fn cocktail_shaker_sort<T: Ord + std::fmt::Debug>(arr: &mut [T]) {
    let len = arr.len();
    if len < 2 {
        return ;
    }
    let mut left = 1;
    let mut right = len - 1;
    while left < right {
        let mut sorted = true;
        // 正向检测 
        for index in left..right {
            if arr[index - 1] > arr[index] {
                arr.swap(index - 1, index);
                sorted = false;
            }
        }
        if sorted {
            break;
        }
        // 收缩边界
        right -= 1;
        sorted = true;
        // 反向检测 
        for index in (left..right).rev() {
            if arr[index - 1] > arr[index] {
                arr.swap(index - 1, index);
                sorted = false;
            }
        }
        if sorted {
            break;
        }
        // 收缩边界
        left += 1;
    }

}