Merge sort an array - Node.js Algorithm

Node.js examples for Algorithm:Sort

Description

Merge sort an array

Demo Code

function merge(a, b) {
  var retArr = [];
  var i = j = 0;/*from  w  w w .j  a  va2  s. c  om*/
  var aLen = a.length;
  var bLen = b.length;
  while (i < aLen || j < bLen) {
    if (i === aLen) {
      retArr.push(b[j]);
      j++;
    } else if (j === bLen) {
      retArr.push(a[i]);
      i++;
    } else if (a[i] < b[j]) {
      retArr.push(a[i]);
      i++;
    } else {
      retArr.push(b[j]);
      j++;
    }
  }
  return retArr;
}

function mergeSort(arr) {
  if (arr.length === 1) return arr;
  var mid = Math.floor(arr.length / 2);
  var left = arr.slice(0, mid);
  var right = arr.slice(mid);
  left = mergeSort(left);
  right = mergeSort(right);
  return merge(left, right);
}

function bottomUpMergeSort(arr) {
  var len = arr.length;
  var left, right, result;
  for (var sz = 1; sz < len; sz += sz) {
    for (var lo = 0; lo < len - sz; lo += 2 * sz) {
      left = arr.slice(lo, lo + sz);
      right = arr.slice(lo + sz, lo + sz + sz);
      result = merge(left, right);
      Array.prototype.splice.apply(arr, [lo, result.length].concat(result));
    }
  }
  return arr;
}

Related Tutorials