rust-algorithms:10-奇偶排序

godme發表於2022-07-25
pub fn odd_even_sort<T: Ord>(arr: &mut [T]) {
    let len = arr.len();
    if len < 2 {
        return ;
    }
    let mut sorted = false;
    while !sorted {
        sorted = true;
        // odd
        for current in (1..len-1).step_by(2) {
            if arr[current] > arr[current + 1] {
                arr.swap(current, current +  1);
                sorted = false;
            }
        }
        // even
        for current in (0..len-1).step_by(2) {
            if arr[current] > arr[current + 1] {
                arr.swap(current, current + 1);
                sorted = false;
            }
        }
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章