Problem 39

Merge Sort Recursion Challenge

Given an array of numbers, return a new array sorted in ascending order using the merge sort algorithm.

Function Signature

mergeSort(array)

Parameters

  • array — an array of integers. May contain positive, negative, or zero values.

Output

Return a new array with all elements sorted from least to greatest.

Constraints

  • The function must use recursion.
  • Do not use Array.prototype.sort.
  • The input array must not be mutated.
  • The function should accept exactly one argument.

Examples

mergeSort([8, 2, 20, 1, 15])  → [1, 2, 8, 15, 20]
mergeSort([5, 4, 3, 2, 1])    → [1, 2, 3, 4, 5]
mergeSort([8, -2, 20, 1, -15]) → [-15, -2, 1, 8, 20]
mergeSort([])                  → []
mergeSort([0])                 → [0]