Skip to main content
Back to ChallengesImplement Merge SortMedium 25 min

Implement Merge Sort

Write a function that takes in an array of integers and returns a sorted version of that array using the Merge Sort algorithm.

Merge sort works by continuously dividing the array in half until it cannot be further divided. This means that if the array becomes empty or has only one element left, the dividing will stop, i.e. it is the base case to stop the recursion. If the array has multiple elements, split the array into halves and recursively invoke the merge sort on each of the halves. Finally, when both halves are sorted, the merge operation is applied.

Examples

Input: arr = [8, 5, 2, 9, 5, 6, 3]
Output: [2, 3, 5, 5, 6, 8, 9]
The array is sorted in ascending order.

Constraints

  • 1 <= arr.length <= 10^5
  • -10^4 <= arr[i] <= 10^4

Complexity Analysis

Time
O(N log N)
arrays are split logarithmically and merged linearly.
Space
O(N)
extra space for the merged arrays.

Test Cases

#1 Standard unsorted array
Input: arr = [8,5,2,9,5,6,3]
Expected: [2,3,5,5,6,8,9]
#2 With negative numbers
Input: arr = [10,-2,3,-1]
Expected: [-2,-1,3,10]
JavaScript
Output
Click "Run Code" to see output here...