Brian Yang
Brian Yang
algorithm designer
Mar 16, 2020 1 min read

Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Solution

function merge(arr1, arr2){
  let result = [];
  const totalElements = arr1.length + arr2.length;

  function compare(i, j) {
    if (i + j >= totalElements) { return; }
    if (j >= arr2.length || (i < arr1.length && arr1[i] < arr2[j])) {
      result.push(arr1[i++]);
    } else {
      result.push(arr2[j++]);
    }
    compare(i, j);
  }
  compare(0, 0);
  return result;
}
comments powered by Disqus