Categories
Uncategorized

Merge 2 sorted Arrays Inplace (JavaScript)

Time complexity: O(n)
Here n represents the sum of the lengths of both the arrays.

Code

// Merge 2 sorted Arrays Inplace (JavaScript)

var a = [1, 2, 3];
var b = [4, 5];

var sort = function(a, b) {
  var alen = a.length - 1;
  var blen = b.length - 1;
  var index = alen + blen + 1;
  while (blen >= 0) {
    if (a[alen] >= b[blen])
      a[index--] = a[alen--];
    else
      a[index--] = b[blen--];
    if (alen < 0) {
      while (blen >= 0) {
        a[index--] = b[blen--];
      }
      break;
    }
// if (blen<0) a's contents are already in place, so we don't need to worry about them.
  }
  return a;
}

console.log(sort(a, b));

Output

[1,2,3,4,5]

Demo