rust-algorithms:5-梳排序

Rust
296
0
0
2022-11-10
pub fn comb_sort<T: Ord>(arr: &mut [T]) {
    let len = arr.len();
    let mut gap = len;
    let shrink = 1.3;
    let mut sorted = false;
    while !sorted {
        gap = (gap as f32 / shrink).floor() as usize;
        // 步进小于1,转化为基础的冒泡 
        if gap <= 1 {
            gap = 1;
            sorted = true;
        }
        // gap > 1时只是作为调整,gap等于1时候化为冒泡 
        for index in 0..len - gap {
            if arr[index] > arr[index + gap] {
                arr.swap(index , index + gap);
                sorted = false;
            }
        }
    }
}