Skip to main content
Intermediate ~15 min read

Merge Sort

Split, sort halves, merge, the reliable O(n log n) workhorse and your first divide-and-conquer algorithm.

Prerequisites: Recursion Basics, Big O Notation & Time Complexity

Merge sort is divide-and-conquer made concrete: split the array into two halves, recursively sort each half, then merge the two sorted halves into one sorted whole. The base case is a single element, trivially sorted. The magic is in the merge: given two sorted lists, one linear pass with two pointers produces a sorted union. No comparisons are ever wasted.

The complexity analysis is a beautiful recurrence: T(n) = 2T(n/2) + O(n), two half-size subproblems plus a linear merge. The recursion tree has log₂(n) levels (halving each time), and each level does O(n) total merge work, giving O(n log n), on EVERY input. No adversarial case, no lucky case. That predictability plus stability (equal elements merge left-first, preserving order) is why merge sort underlies Timsort, the default sort of Python and Java.

Implementation

merge-sort.js
// Pure: returns a new sorted array. Stable. O(n) extra space.
function mergeSort(arr) {
  if (arr.length <= 1) return [...arr];        // base case

  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));   // conquer left half
  const right = mergeSort(arr.slice(mid));     // conquer right half
  return merge(left, right);                   // combine
}

function merge(a, b) {
  const out = [];
  let i = 0, j = 0;
  while (i < a.length && j < b.length) {
    if (a[i] <= b[j]) out.push(a[i++]);   // <= keeps it stable: left wins ties
    else out.push(b[j++]);
  }
  while (i < a.length) out.push(a[i++]);  // drain the leftovers
  while (j < b.length) out.push(b[j++]);
  return out;
}

Trace: [38, 27, 43, 3]

  1. 1

    Split down

    [38, 27, 43, 3] → [38, 27] + [43, 3] → [38] + [27] and [43] + [3]. Four singletons, all trivially sorted.

  2. 2

    Merge up (level 1)

    merge([38], [27]): 27 ≤ 38 → [27, 38]. merge([43], [3]) → [3, 43].

  3. 3

    Merge up (level 2)

    merge([27, 38], [3, 43]): 3<27 take 3; 27<43 take 27; 38<43 take 38; drain 43 → [3, 27, 38, 43].

  4. 4

    Cost audit

    2 levels of halving ⇒ log₂4 = 2; each level merged 4 elements total ⇒ O(n log n) = 8 merge-steps. Compare bubble sort's worst case of 6 comparisons on just 4 items, the gap explodes as n grows.

Operation / caseCostNotes
Time (best, average, worst)O(n log n)input-independent, its superpower
SpaceO(n)merge buffer + recursion O(log n)
Stable?Yeswith the <= tie-break in merge
Parallelizes?Yeshalves sort independently

Check your understanding

  1. 1.Why is the merge step O(n) for merging two sorted halves of total length n?
  2. 2.The recurrence T(n) = 2T(n/2) + O(n) resolves to:
  3. 3.Compared with quicksort, merge sort's deciding advantages are:

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Merge Sort

Play, pause, and scrub the real algorithm step by step.

Keep going