< 返回我的博客

iiicp 发表于 2022-04-29 00:52

fn merge(vec: &mut Vec<i32>, start: usize, mid: usize, end: usize) {
    let mut t = Vec::new();
    for i in start..=end {
        t.push(vec[i]);
    }
    let mut i:usize  = 0;
    let new_mid = mid - start;
    let mut j = new_mid + 1;
    let mut k  = start;
    while i <= new_mid && j < t.len() {
        if t[i] <= t[j] {
            vec[k] = t[i];
            k += 1;
            i += 1;
        }else {
            vec[k] = t[j];
            k += 1;
            j += 1;
        }
    }

    while i <= new_mid {
        vec[k] = t[i];
        k += 1;
        i += 1;
    }

    while j < t.len() {
        vec[k] = t[j];
        k += 1;
        j += 1;
    }
}

fn merge_sort(vec : &mut Vec<i32>, start: usize, end: usize) {
    if start >= end {
        return;
    }
    let mid = start + (end - start)/2;
    merge_sort(vec, start, mid);
    merge_sort(vec, mid+1, end);
    merge(vec, start, mid, end);
}

fn main() {
    let mut v = vec![8,6,7,5,0,100,-1,8,9,2,11];
    let len = v.len();
    merge_sort(&mut v, 0, len-1);

    for n in v.iter() {
        print!("{},", n);
    }
}

评论区

写评论

还没有评论

1 共 0 条评论, 1 页