Solution Review: Merge Two Sorted Arrays
This review provides a detailed analysis of the different ways to solve the "Merge Two Sorted Arrays" challenge.
Solution #
Press + to interact
fn merge_sorted_arrays(array1: &Vec<i32>, array2: &Vec<i32>) -> Vec<i32>{let mut array3: Vec<i32>= vec![0; array1.len()+array2.len()];let mut i = 0;let mut j = 0;let mut k = 0;while i<array1.len() && j<array2.len() {if array1[i] <= array2[j]{array3[k] = array1[i];i+=1;k+=1;}else{array3[k] = array2[j];j+=1;k+=1;}}while i<array1.len(){array3[k] = array1[i];i+=1;k+=1;}while j<array2.len(){array3[k] = array2[j];j+=1;k+=1;}return array3;}
Explanation
Start by creating a new vector array3
. If the first array element is less than the second array element, then copy the first array element in array3
. Copy the second array element in the new array and increment both arrays, which is array3
and the array from which the element is being copied . If ...
Access this course and 1400+ top-rated courses and projects.