Skip to content

Instantly share code, notes, and snippets.

@Mec-iS
Created April 18, 2019 15:23
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 Mec-iS/3c4e500307fb5a18f0a8e30737561c8b to your computer and use it in GitHub Desktop.
Save Mec-iS/3c4e500307fb5a18f0a8e30737561c8b to your computer and use it in GitHub Desktop.
Merge subroutine like a rustaceans
fn Merge(c: Vec<i32>, d: Vec<i32>) -> Vec<i32> {
let l: usize = c.len() + d.len();
// initialize result array
let mut b: Vec<i32> = vec!(0; l);
// initialize readers indexes
let mut i: usize = 0;
let mut j: usize = 0;
for k in 0..l {
// get value or None from the two array
let (c_value, d_value) = (c.get(i), d.get(j));
// safe and neat
match (c_value, d_value) {
(None, None) => break,
(None, Some(_)) => {
b[k] = d[j];
j += 1;
},
(Some(_), None) => {
b[k] = c[i];
i += 1;
},
(Some(_), Some(_)) => match c_value.unwrap() < d_value.unwrap() {
true => {
b[k] = c[i];
b[k+1] = d[j];
i += 1;
},
false => {
b[k] = d[j];
b[k+1] = c[i];
j += 1;
}
}
}
}
return b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment