Split the array recursively, sort each half, then merge two sorted runs into one sorted result.

Algorithm

Basic Implementation

basic.js
function mergeSort(values) {
    if (values.length <= 1) {
        return values;
    }
    const mid = Math.floor(values.length / 2);
    const left = mergeSort(values.slice(0, mid));
    const right = mergeSort(values.slice(mid));
    const merged = [];
    let i = 0;
    let j = 0;
    while (i < left.length && j < right.length) {
        if (left[i] <= right[j]) {
            merged.push(left[i++]);
        } else {
            merged.push(right[j++]);
        }
    }
    return merged.concat(left.slice(i)).concat(right.slice(j));
}

const arr = [5, 1, 4, 2, 8];
console.log(JSON.stringify(mergeSort(arr)));

The pinned input is [5, 1, 4, 2, 8]. The diagrams show the split into recursive halves, the sorted subarrays, and the final merge choices.

Step 1 - Split the input

The first midpoint splits [5, 1, 4, 2, 8] into left [5, 1] and right [4, 2, 8].

Top-down split used by merge_sort.[5,1,4,2,8]mid = 2[5,1]left[4,2,8]right

Step 2 - Sorted halves return

Recursive calls return [1, 5] and [2, 4, 8] before the final merge begins.

Returned subarrays before the final merge.sidebefore sortafter sortleft[5, 1][1, 5]right[4, 2, 8][2, 4, 8]

Step 3 - Merge by taking smaller fronts

Take 1 from left, then 2 and 4 from right, then the remaining 5 and 8.

Final merge produces [1, 2, 4, 5, 8].choiceleft frontright frontmergedtake 112[1]take 252[1, 2]take 454[1, 2, 4]extend58[1, 2, 4, 5, 8]

Complexity

  • Time: O(n log n)
  • Space: O(n)
  • Stable: yes

Implementation notes

  • JavaScript stores the input as a const Array of Number values. mergeSort returns a sorted array instead of mutating the original arr; only length-0 or length-1 base cases return the existing array reference.
  • Each recursive split uses Math.floor(values.length / 2) plus values.slice(0, mid) and values.slice(mid), so the left and right halves are copied arrays before the recursive calls.
  • merge state is held in a fresh merged array and index variables i and j. The numeric comparison left[i] <= right[j] takes the left value on ties, preserving stability for equal Number values.
  • Values are appended with merged.push(...); remaining tails are appended via merged.concat(left.slice(i)).concat(right.slice(j)), which allocates the tail slices and concatenated result arrays.
  • The replay-visible states split [5, 1, 4, 2, 8] into [5, 1] and [4, 2, 8], sort them to [1, 5] and [2, 4, 8], then merge [1, 2, 4, 5, 8]. console.log(JSON.stringify(mergeSort(arr))) creates the compact output string [1,2,4,5,8]; temporary arrays and strings are handled by the JavaScript runtime GC.
divide and conquer Each recursive call solves a smaller sorted subproblem.
merge step Two sorted halves are combined by repeatedly taking the smaller front item.