merge sort in javascript

Here's the implementation of Merge Sort in JavaScript using recursion:

index.tsx
function mergeSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }

  const middleIndex = Math.floor(arr.length / 2);
  const leftArr = arr.slice(0, middleIndex);
  const rightArr = arr.slice(middleIndex);

  return merge(mergeSort(leftArr), mergeSort(rightArr));
}

function merge(leftArr, rightArr) {
  const resultArr = [];

  while (leftArr.length && rightArr.length) {
    if (leftArr[0] < rightArr[0]) {
      resultArr.push(leftArr.shift());
    } else {
      resultArr.push(rightArr.shift());
    }
  }

  return resultArr.concat(leftArr, rightArr);
}
565 chars
26 lines

To use this Merge Sort implementation, simply call the mergeSort() function and pass in an array:

index.tsx
const unsortedArr = [5, 2, 6, 3, 1, 4];
const sortedArr = mergeSort(unsortedArr);

console.log(sortedArr); // [1, 2, 3, 4, 5, 6]
129 chars
5 lines

gistlibby LogSnag