0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Merge Two Sorted Arrays

You can merge two sorted arrays in JavaScript by using a function that compares elements from both arrays and adds the smaller one to a new array, like function mergeSortedArrays(arr1, arr2) { let i = 0, j = 0, merged = []; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) merged.push(arr1[i++]); else merged.push(arr2[j++]); } return merged.concat(arr1.slice(i)).concat(arr2.slice(j)); }.
📋

Examples

Input[[1,3,5],[2,4,6]]
Output[1,2,3,4,5,6]
Input[[0,2,4,8],[1,3,5,7]]
Output[0,1,2,3,4,5,7,8]
Input[[],[1,2,3]]
Output[1,2,3]
🧠

How to Think About It

To merge two sorted arrays, start by comparing the first elements of both arrays. Pick the smaller element and add it to a new array. Move the pointer forward in the array from which you took the element. Repeat this until one array is fully added, then add the remaining elements from the other array.
📐

Algorithm

1
Initialize two pointers at the start of each array and an empty array for the result.
2
Compare the elements at the pointers of both arrays.
3
Add the smaller element to the result array and move that pointer forward.
4
Repeat until one array is fully traversed.
5
Add any remaining elements from the other array to the result.
6
Return the merged array.
💻

Code

javascript
function mergeSortedArrays(arr1, arr2) {
  let i = 0, j = 0;
  const merged = [];
  while (i < arr1.length && j < arr2.length) {
    if (arr1[i] < arr2[j]) {
      merged.push(arr1[i]);
      i++;
    } else {
      merged.push(arr2[j]);
      j++;
    }
  }
  return merged.concat(arr1.slice(i)).concat(arr2.slice(j));
}

console.log(mergeSortedArrays([1,3,5], [2,4,6]));
Output
[1,2,3,4,5,6]
🔍

Dry Run

Let's trace merging [1,3,5] and [2,4,6] through the code

1

Start with pointers i=0, j=0

arr1[i]=1, arr2[j]=2, merged=[]

2

Compare arr1[i] and arr2[j]

1 < 2, so push 1, i=1, merged=[1]

3

Compare arr1[i] and arr2[j]

3 > 2, so push 2, j=1, merged=[1,2]

4

Compare arr1[i] and arr2[j]

3 < 4, so push 3, i=2, merged=[1,2,3]

5

Compare arr1[i] and arr2[j]

5 > 4, so push 4, j=2, merged=[1,2,3,4]

6

Compare arr1[i] and arr2[j]

5 < 6, so push 5, i=3, merged=[1,2,3,4,5]

7

arr1 exhausted, add remaining arr2 elements

merged=[1,2,3,4,5,6]

ijmerged
00[]
10[1]
11[1,2]
21[1,2,3]
22[1,2,3,4]
32[1,2,3,4,5]
33[1,2,3,4,5,6]
💡

Why This Works

Step 1: Compare elements

The code compares the current elements of both arrays using if (arr1[i] < arr2[j]) to decide which to add next.

Step 2: Add smaller element

It adds the smaller element to the merged array and moves the pointer forward in that array.

Step 3: Add remaining elements

After one array is fully added, the remaining elements of the other array are concatenated to the result using concat.

🔄

Alternative Approaches

Using built-in sort after concatenation
javascript
function mergeSortedArrays(arr1, arr2) {
  return arr1.concat(arr2).sort((a,b) => a - b);
}

console.log(mergeSortedArrays([1,3,5], [2,4,6]));
Simpler code but less efficient because it sorts the whole combined array instead of merging sorted arrays directly.
Using recursion
javascript
function mergeSortedArrays(arr1, arr2) {
  if (!arr1.length) return arr2;
  if (!arr2.length) return arr1;
  if (arr1[0] < arr2[0]) {
    return [arr1[0]].concat(mergeSortedArrays(arr1.slice(1), arr2));
  } else {
    return [arr2[0]].concat(mergeSortedArrays(arr1, arr2.slice(1)));
  }
}

console.log(mergeSortedArrays([1,3,5], [2,4,6]));
Elegant but less efficient due to many array slices and function calls.

Complexity: O(n + m) time, O(n + m) space

Time Complexity

The algorithm goes through each element of both arrays once, so it takes time proportional to the sum of their lengths.

Space Complexity

It creates a new array to hold all elements, so space used is proportional to the total number of elements.

Which Approach is Fastest?

The two-pointer merge is fastest because it avoids sorting the combined array, unlike the concat-and-sort method.

ApproachTimeSpaceBest For
Two-pointer mergeO(n + m)O(n + m)Merging already sorted arrays efficiently
Concat and sortO((n + m) log(n + m))O(n + m)Quick code but slower for large arrays
Recursive mergeO(n + m)O(n + m)Readable code but less efficient due to recursion overhead
💡
Use two pointers to efficiently merge sorted arrays without sorting the combined array.
⚠️
Trying to merge by simply concatenating arrays without sorting or merging properly.