Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Move all zeros in Rust (#5731)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <[email protected]>
  • Loading branch information
Riyazul555 and MdRiyazulIslam authored Jun 12, 2024
1 parent ceec230 commit c634e4d
Showing 1 changed file with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
fn move_zeroes(arr: &mut Vec<i32>) {
let mut non_zero_index = 0;

// First pass: Move all non-zero elements to the front of the array
for i in 0..arr.len() {
if arr[i] != 0 {
arr[non_zero_index] = arr[i];
non_zero_index += 1;
}
}

// Second pass: Fill the remaining positions with zeroes
for i in non_zero_index..arr.len() {
arr[i] = 0;
}
}

fn main() {
let mut arr = vec![0, 1, 0, 3, 12];
println!("Original array: {:?}", arr);

move_zeroes(&mut arr);

println!("Array after moving zeroes: {:?}", arr);
}

0 comments on commit c634e4d

Please sign in to comment.