rust-algorithms:5-梳排序

godme發表於2022-07-25
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;
            }
        }
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章