JavaScript- Merge two Sorted Arrays
These are the following ways to merge two sorted arrays:
1. Using Two Pointers (Efficient For Large Arrays)
This approach involves using two pointers, one for each array, and comparing their elements as you iterate through them. This method works efficiently in O(n + m) time, where n and m are the lengths of the two arrays.
function fun(a1, a2) {
let i = 0, j = 0, res = [];
while (i < a1.length && j < a2.length) {
if (a1[i] < a2[j]) {
res.push(a1[i]);
i++;
} else {
res.push(a2[j]);
j++;
}
}
// If any elements remain in a1 or a2, add them to the res
while (i < a1.length) {
res.push(a1[i]);
i++;
}
while (j < a2.length) {
res.push(a2[j]);
j++;
}
return res;
}
const a1 = [1, 3, 5, 7];
const a2 = [2, 4, 6, 8];
console.log(fun(a1, a2));
Output
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
2. Using concat() and sort() (Less Efficient)
You can merge both arrays using concat() and then use sort() to sort the merged array. However, this method has a time complexity of O((n + m) * log(n + m)), where n and m are the lengths of the arrays, due to the sorting step.
const a1 = [1, 3, 5, 7];
const a2 = [2, 4, 6, 8];
let res = a1.concat(a2).sort((a, b) => a - b);
console.log(res);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
3. Using push() in a Loop (Manual Merge and Less Efficient)
This approach manually merges the arrays using push() without explicitly using two pointers or the sort() function. It iterates through both arrays and adds the elements in sorted order.
const a1 = [1, 3, 5, 7];
const a2 = [2, 4, 6, 8];
let res = [];
while (a1.length || a2.length) {
if (!a1.length) {
res.push(a2.shift());
} else if (!a2.length) {
res.push(a1.shift());
} else if (a1[0] < a2[0]) {
res.push(a1.shift());
} else {
res.push(a2.shift());
}
}
console.log(res);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8 ]
4. Using reduce() (Functional and Efficient Approach)
This approach uses reduce() function to iterate over a1 while simultaneously inserting elements from a2 into the accumulator (acc) array in sorted order. The shift() method is used to remove elements from a2 when necessary, ensuring the merged array is sorted.
function fun(a1, a2) {
return a1.reduce((acc, val) => {
while (a2.length && a2[0] <= val) {
acc.push(a2.shift());
}
acc.push(val);
return acc;
}, [...a2]);
}
const a1 = [1, 3, 5, 7];
const a2 = [2, 4, 6, 8];
console.log(fun(a1, a2));
Output
[ 2, 4, 6, 8, 1, 2, 3, 4, 5, 6, 7 ]