Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merge two sorted arrays to form a resultant sorted array in JavaScript
We are required to write a JavaScript function that takes in two sorted arrays of numbers. The function should merge the two arrays together to form a resultant sorted array and return that array.
For example, if the two arrays are:
const arr1 = [2, 6, 6, 8, 9]; const arr2 = [1, 4, 5, 7];
Then the output array should be:
[1, 2, 4, 5, 6, 6, 7, 8, 9]
Method 1: Using Two Pointers Technique
The most efficient approach is the two-pointers technique, which compares elements from both arrays and builds the result array in sorted order:
const arr1 = [2, 6, 6, 8, 9];
const arr2 = [1, 4, 5, 7];
const mergeSortedArrays = (arr1, arr2) => {
let i = 0, j = 0;
const result = [];
// Compare elements from both arrays
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
result.push(arr1[i]);
i++;
} else {
result.push(arr2[j]);
j++;
}
}
// Add remaining elements from arr1
while (i < arr1.length) {
result.push(arr1[i]);
i++;
}
// Add remaining elements from arr2
while (j < arr2.length) {
result.push(arr2[j]);
j++;
}
return result;
};
const merged = mergeSortedArrays(arr1, arr2);
console.log(merged);
[1, 2, 4, 5, 6, 6, 7, 8, 9]
Method 2: Using Spread Operator and Sort
A simpler but less efficient approach is to concatenate arrays and sort the result:
const arr1 = [2, 6, 6, 8, 9];
const arr2 = [1, 4, 5, 7];
const mergeSortedArrays = (arr1, arr2) => {
return [...arr1, ...arr2].sort((a, b) => a - b);
};
const merged = mergeSortedArrays(arr1, arr2);
console.log(merged);
[1, 2, 4, 5, 6, 6, 7, 8, 9]
How the Two Pointers Method Works
The algorithm uses two pointers to traverse both arrays simultaneously:
- Compare current elements from both arrays
- Push the smaller element to the result array
- Move the pointer of the array from which element was taken
- Repeat until one array is exhausted
- Add remaining elements from the non-exhausted array
Comparison
| Method | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Two Pointers | O(m + n) | O(m + n) | High - leverages sorted nature |
| Spread & Sort | O((m + n) log(m + n)) | O(m + n) | Lower - doesn't use sorted property |
Conclusion
The two pointers technique is the optimal solution for merging sorted arrays with O(m + n) time complexity. Use the spread operator method only for simplicity when performance isn't critical.
