Given two arrays sorted in ascending order, write a program that merges the two arrays in ascending order and prints them.
3
1 3 5
5
2 3 6 7 9
Outputs an array sorted in ascending order.
1 2 3 3 5 6 7 9
dot spread
& sort()
function solution(arr1, arr2) {
return [...arr1, ...arr2].sort((a, b) => a - b);
}
function solution(arr1, arr2) {
let answer = [];
let n = arr1.length,
m = arr2.length,
p1 = (p2 = 0);
while (p1 < n && p2 < m) {
// answer.push(arr1[p1++]) means push arr1[p1] first, then increase p1
// e.g) arr.push(3++) is arr.push(3) then it is gonna be 4
if (arr1[p1] <= arr2[p2]) answer.push(arr1[p1++]);
else answer.push(arr2[p2++]);
}
while (p1 < n) answer.push(arr1[p1++]);
while (p2 < m) answer.push(arr2[p2++]);
return answer;
}