Open lpatmo opened 5 years ago
function mergeSorted(arr1,arr2) {
let results = [];
let i = 0, j = 0;
while(i < arr1.length && j < arr2.length) {
if (arr2[j] > arr1[i]) {
results.push(arr1[i])
i++;
} else {
results.push(arr2[j]);
j++;
}
}
//once we've exceeded the index on one of them (i.e. one array is longer than the other one)
while (i < arr1.length) {
results.push(arr1[i])
i++;
}
while (j < arr1.length) {
results.push(arr2[j])
j++;
}
return results;
}
Recursive solution:
function mergeSorted(arr1, arr2){
//base case: arr1 and arr2 are empty, return empty arr
//if arr1 empty, return arr2
// if arr2 empty, return arr1
// otherwise, compare arr1[0] and arr2[0] and return the smallest number + merge(arr1.slice(1), arr2)
if (arr1.length === 0 && arr2.length === 0) {
return [];
} else if (arr1.length === 0 && arr2.length > 0) {
return arr2;
} else if (arr2.length === 0 && arr1.length > 0) {
return arr1;
} else if (arr1[0] < arr2[0]) {
return [arr1[0]].concat(merge(arr1.slice(1), arr2))
} else if (arr1[0] > arr2[0]) {
return [arr2[0]].concat(merge(arr1, arr2.slice(1)))
}
}
What about the unittests? Adding in unittests is a common requirement in coding exams.
One liner es flavored lazy solution
const merge = (arr1=[], arr2=[]) => ([...arr1, ...arr2].sort((a, b)=> a - b))