rust implements bubble sort through iteration

Introduction to Bubble Sort Algorithm

~Slightly~

Iteration abort condition

The "swap" event does not occur during the traversal of the sequence from beginning to end

accomplish


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);
}

Briefly

Adds an identifier flag, which is initialized to true on each traversal and set to true when a swap occurs. Check whether an exchange has occurred at the end of each traversal, and if so, start the next round of traversal.

ps: compile

Short programs written in rust are not suitable for building projects with cargo, so you need to compile them directly with rustc. Assuming the above code is saved as bubblesort.rs, the compile command I use is

rustc --cfg bubblesort bubblesort.rs

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326928587&siteId=291194637