rust通过迭代实现冒泡排序

冒泡排序算法简介

~略~

迭代中止条件

数列从头到尾遍历过程中未发生“交换”事件

实现


fn do_exchange(list: &mut Vec<usize>,index:usize) {
    let temp = list[index+1];
    list[index+1] = list[index];
    list[index] = temp;
}

fn next(list: &mut Vec<usize>,index:usize,is_stable: bool ) {
    let length = list.len();
    let flag = list[index] < list[index+1];//is need changed
    if !flag{
        do_exchange(list,index);
    }
    let flag = flag && is_stable;
    if index + 2 < length{
        next(list,index+1,flag);
    }else if flag {
        return;
    }else {
        next(list,0,true)
    }
}

fn sort(list: &mut Vec<usize>) {
    next(list,0,true);
}

fn main() {
    let mut list : Vec<usize> = vec![2,3,1,4,6,8,0,5];
    sort(&mut list);
    println!("{:?}",list);
}

简述

添加一个标识符flag,每次遍历初始化为true,当发生交换时置为true。每次遍历结束时检测是否发生过交换,如果是开始下一轮遍历。

ps: 编译

rust编写的简短程序不适合使用cargo建立project,这时就需要直接使用rustc进行编译。假设上述代码保存为bubblesort.rs,则我使用的编译命令为

rustc --cfg bubblesort bubblesort.rs

猜你喜欢

转载自my.oschina.net/u/3703365/blog/1789785