Merge two sorted array in Javascript

Merge two sorted arrays in Javascript

Arrays, Data Structure, Javascript, Trending

In this blog we are writing program to merge two sorted arrays in javascript.

Problem :  Given two sorted arrays, merge them into a new array that is also sorted.

Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}

Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}

We will use Greedy Approach to write this program with efficient technique.

function mergeTwo(arr1, arr2) {
  let merged = [];
  let index1 = 0;
  let index2 = 0;
  let current = 0;

  while (current < (arr1.length + arr2.length)) {
      let unmerged1 = arr1[index1];
      let unmerged2 = arr2[index2];

      // if next comes from arr1
      if (unmerged1 < unmerged2) {
          merged[current] = unmerged1;
          index1++;

      // if next comes from arr2
      } else {
          merged[current] = unmerged2;
          index2++;
      }

      current++;
  }
const arr1 = [3, 5, 6, 10, 11, 20];
const arr2 = [1, 2, 7, 8, 15, 19];
mergeTwo(arr1, arr2);

Time Complexity : O(n)

Space Complexity: O(n)

In Javascript we can also use inbuilt functions to merge two arrays as show below:

function mergeTwo(arr1, arr2) {
  let result = [...arr1, ...arr2];
  return result.sort((a,b) => a-b);
}

const arr1 = [3, 5, 6, 10, 11, 20];
const arr2 = [1, 2, 7, 8, 15, 19];

mergeTwo(arr1, arr2); 

2 comments

Leave a Reply