call(back)
Algorithms & Data StructuresmediumSign in to star problems

Merge Sort

Implement merge sort: return a new array with the numbers of arr in ascending order, without using the built-in sort. Equal values must keep their relative order (stable).

mergeSort([9, 3, 6, 2, 1, 11])  ->  [1, 2, 3, 6, 9, 11]
mergeSort([])                   ->  []

Hints

Hint 1

Base case: zero or one element is sorted. Otherwise sort the two halves recursively and merge.

Hint 2

Merge with an index into each half, taking from the left on ties for stability, then append whatever remains.

Asked at