How to sort a vctor that consists of only 0s and 1s in Rust

1 Answer

0 votes
fn sort_binary_vector(arr: &mut Vec<i32>) {
    let mut left = 0;                     // Index to track the left side
    let mut right = arr.len() - 1;        // Index to track the right side

    while left < right {
        // If the left index is at 0, move it forward
        if arr[left] == 0 {
            println!("left: {}", left);
            left += 1;
        }
        // If the right index is at 1, move it backward
        else if arr[right] == 1 {
            println!("right: {}", right);
            right -= 1;
        }
        // If left is 1 and right is 0, swap them
        else {
            arr.swap(left, right);
            println!("swap() left: {} right: {}", left, right);
            left += 1;
            right -= 1;
        }
    }
}

fn main() {
    // Input: Binary vector
    let mut arr = vec![1, 0, 1, 0, 1, 0, 0, 1, 0];

    // Sort the binary vector
    sort_binary_vector(&mut arr);

    // Output the sorted vector
    print!("Sorted vector: ");
    for num in &arr {
        print!("{} ", num);
    }
}



/*
run:

swap() left: 0 right: 8
left: 1
right: 7
swap() left: 2 right: 6
left: 3
swap() left: 4 right: 5
Sorted vector: 0 0 0 0 0 1 1 1 1

*/

 



answered Sep 3 by avibootz
...