DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 95

The task is to implement the merge sort.

The boilerplate code

function mergeSort(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If the array is empty or has 1 element, it is already sorted

if (arr.length <= 1) return arr;
Enter fullscreen mode Exit fullscreen mode

Create a helper function that returns a new sorted array. The function recursively splits the array in half.

function mergeSortHelper(arr) {
  if (arr.length <= 1) return arr;

  const mid = Math.floor(arr.length / 2);
Enter fullscreen mode Exit fullscreen mode

Sort each half independently, and merge the sorted halves

  const left = mergeSortHelper(arr.slice(0, mid));
  const right = mergeSortHelper(arr.slice(mid));

  return merge(left, right);
Enter fullscreen mode Exit fullscreen mode

Copy the sorted array back into the original array

const sorted = mergeSortHelper(arr);
  for (let i = 0; i < arr.length; i++) {
    arr[i] = sorted[i];
  }

Enter fullscreen mode Exit fullscreen mode

Return the original array

return arr;
Enter fullscreen mode Exit fullscreen mode

Given two already sorted arrays, merge both arrays by repeatedly pushing the smaller element to the front

function merge(left, right) {
 const result = [];
  let i = 0, j = 0;

  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) {
      result.push(left[i++]);
    } else {
      result.push(right[j++]);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Append any remaining values

return result
    .concat(left.slice(i))
    .concat(right.slice(j));
Enter fullscreen mode Exit fullscreen mode

The final code

function mergeSort(arr) {
  // your code here
  if(arr.length <= 1) return arr;

  const sorted = mergeSortHelper(arr);

  for(let i = 0; i < arr.length; i++) {
    arr[i] = sorted[i];
  }
  return arr;
}

function mergeSortHelper(arr) {
  if(arr.length <= 1) return arr;

  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));

  return merge(left, right);
}

function merge(left, right) {
  const result = [];
  let i = 0;
  let j = 0;

  while(i < left.length && j < right.length) {
    if(left[i] <= right[j]) {
      result.push(left[i]);
      i++;
    } else {
      result.push(right[j]);
      j++;
    }
  }
  return result
  .concat(left.slice(i))
  .concat(right.slice(j));
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)