Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Created June 4, 2021 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snewcomer/aa858071696b0a2b0c6a7b041f7929fa to your computer and use it in GitHub Desktop.
Save snewcomer/aa858071696b0a2b0c6a7b041f7929fa to your computer and use it in GitHub Desktop.
Rust Sort 0's to back
// Your last Rust code is saved below:
fn move_to_back(v: &Vec<u32>) -> Vec<u32> {
// extra memory
let mut res = vec![];
let mut num_of_zeros = 0;
for i in v.iter() {
if *i != 0 as u32 {
res.push(*i);
} else {
num_of_zeros += 1;
}
}
res.sort();
while num_of_zeros != 0 {
res.push(0 as u32);
num_of_zeros -= 1;
}
res
}
fn move_to_back_in_place(v: &mut Vec<u32>) -> Vec<u32> {
v.sort();
// if value in vector is 0, we will mark this as sorted last (ascending)
v.sort_by_key(|a| *a == 0);
v.to_vec()
}
fn main() {
let input = vec![1, 0, 0, 2, 3, 4, 0, 6];
let res = move_to_back(&input);
dbg!(res);
let input = vec![1, 2, 3, 4, 8, 6];
let res = move_to_back(&input);
dbg!(res);
let mut input = vec![1, 0, 0, 2, 3, 4, 8, 6, 0];
let res = move_to_back_in_place(&mut input);
dbg!(res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment