To learn Rust, I tried to write a function that takes two sorted arrays of integers and interleaves them into one longer sorted array.
Is this approach ok? Have I made any mistakes?
fn main() {
let a = [1, 3, 4, 4];
let b = [0, 2, 5, 6];
println!("{:?}", merge(&a, &b));
}
fn merge(list_a : &[i32; 4], list_b : &[i32; 4]) -> [i32; 8] {
let mut merged_list: [i32; 8] = [0; 8];
let mut idx = 0;
let mut idx_b = 0;
for a in list_a.iter() {
while idx_b < list_b.len() && list_b[idx_b] < *a {
merged_list[idx] = list_b[idx_b];
idx_b +=1;
idx += 1;
}
merged_list[idx] = *a;
idx += 1;
}
for b in list_b[idx_b..].iter() {
merged_list[idx] = *b;
idx += 1;
}
println!("{:?}", merged_list);
merged_list
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_merge() {
let a = [1, 3, 3, 7];
let b = [0, 4, 6, 8];
assert_eq!(merge(&a, &b), [0, 1, 3, 3, 4, 6, 7, 8]);
}
}