~略~算法
数列从头至尾遍历过程当中未发生“交换”事件spa
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。每次遍历结束时检测是否发生过交换,若是是开始下一轮遍历。code
rust编写的简短程序不适合使用cargo创建project,这时就须要直接使用rustc进行编译。假设上述代码保存为bubblesort.rs,则我使用的编译命令为排序
rustc --cfg bubblesort bubblesort.rs事件