3. Merge Sort

Divide, conquer, merge — the gateway to recursive thinking

You have a shuffled deck of cards and need to put them in order. One strategy: split the deck in half, sort each half separately, then merge the two sorted halves back together. Each half can be sorted the same way — split it, sort the pieces, merge. Keep going until you're down to single cards, which are already sorted by definition.

That's merge sort — one of the most important algorithms in computer science. Invented by John von Neumann in 1945, it's the textbook example of divide and conquer, and it guarantees O(n log n) performance no matter what input you throw at it.

The Divide-and-Conquer Idea

Merge sort follows a three-step pattern that shows up again and again in algorithm design:

  1. Divide

    Split the array into two halves at the midpoint.

  2. Conquer

    Recursively sort each half. The base case is an array of length 0 or 1 — it's already sorted.

  3. Combine

    Merge the two sorted halves into a single sorted array. This is where the real work happens.

The key insight

Merging two sorted arrays is easy — you just compare the front elements and pick the smaller one, over and over. The genius of merge sort is reducing the hard problem (sorting) to the easy problem (merging) through recursion.

A Simple Example

Sorting [38, 27, 43, 3, 9, 82, 10]

Split:  [38, 27, 43, 3, 9, 82, 10]
        /                        \
 [38, 27, 43, 3]          [9, 82, 10]
    /         \              /       \
[38, 27]   [43, 3]      [9, 82]    [10]
 /    \     /    \       /    \       |
[38]  [27] [43]  [3]   [9]  [82]    [10]

Merge back up: [38] [27] [43] [3] [9] [82] [10] \ / \ / \ / | [27, 38] [3, 43] [9, 82] [10] \ / \ / [3, 27, 38, 43] [9, 10, 82] \ / [3, 9, 10, 27, 38, 43, 82]

The array is split all the way down to individual elements, then merged back together in sorted order at each level.

The Merge Operation in Detail

The merge step is the heart of the algorithm. Given two sorted arrays, it produces one sorted array containing all elements from both. The technique is called a two-pointer merge:

  1. Set up two pointers

    Pointer i starts at the beginning of the left half. Pointer j starts at the beginning of the right half. Create an empty result array.

  2. Compare and pick

    Compare left[i] and right[j]. Append the smaller one to the result and advance that pointer. If they're equal, take from the left (this preserves stability).

  3. Drain the remainder

    When one side is exhausted, append all remaining elements from the other side.

Merging [3, 27, 38, 43] and [9, 10, 82]

Left:  [3, 27, 38, 43]    Right: [9, 10, 82]    Result: []
      ^                          ^

Compare 3 vs 9 → take 3 Result: [3] ^ ^

Compare 27 vs 9 → take 9 Result: [3, 9] ^ ^

Compare 27 vs 10 → take 10 Result: [3, 9, 10] ^ ^

Compare 27 vs 82 → take 27 Result: [3, 9, 10, 27] ^ ^

Compare 38 vs 82 → take 38 Result: [3, 9, 10, 27, 38] ^ ^

Compare 43 vs 82 → take 43 Result: [3, 9, 10, 27, 38, 43] ^

Right remains: drain 82 Result: [3, 9, 10, 27, 38, 43, 82]

Pseudocode

function mergeSort(arr):
    if length(arr) <= 1:
        return arr

    mid = length(arr) / 2
    left  = mergeSort(arr[0..mid])
    right = mergeSort(arr[mid..end])

    return merge(left, right)


function merge(left, right):
    result = []
    i = 0
    j = 0

    while i < length(left) and j < length(right):
        if left[i] <= right[j]:      // <= preserves stability
            result.append(left[i])
            i = i + 1
        else:
            result.append(right[j])
            j = j + 1

    // Append remaining elements
    while i < length(left):
        result.append(left[i])
        i = i + 1

    while j < length(right):
        result.append(right[j])
        j = j + 1

    return result

The Full Recursion Tree

Let's trace every recursive call for our example array. The tree splits top-down, then merges bottom-up:

Splitting phase (top-down)

Level 0:  mergeSort([38, 27, 43, 3, 9, 82, 10])
Level 1:  mergeSort([38, 27, 43, 3])        mergeSort([9, 82, 10])
Level 2:  mergeSort([38, 27])  mergeSort([43, 3])   mergeSort([9, 82])  mergeSort([10])
Level 3:  ms([38]) ms([27])  ms([43]) ms([3])  ms([9]) ms([82])    (base case)

Merging phase (bottom-up)

Level 3:  [38]  [27]    [43]  [3]    [9]  [82]    [10]
             ↘   ↙        ↘   ↙       ↘   ↙         |
Level 2:  [27, 38]      [3, 43]     [9, 82]       [10]
               ↘          ↙              ↘          ↙
Level 1:  [3, 27, 38, 43]           [9, 10, 82]
                    ↘                    ↙
Level 0:  [3, 9, 10, 27, 38, 43, 82]

There are log2(7) ≈ 3 levels of recursion, and at each level the total work across all merges is O(n). That's why the total time is O(n log n).

Stability: Why It Matters

A sorting algorithm is stable if equal elements keep their original relative order after sorting. Merge sort is stable — and here's why:

The stability guarantee

In the merge step, when left[i] == right[j], we always take from the left side first. Since the left half came before the right half in the original array, equal elements preserve their original order.

Why does stability matter? Consider sorting a spreadsheet of employees first by name, then by department. With a stable sort, employees within the same department stay in alphabetical order. An unstable sort could scramble the names within each department.

Stability in action

Original:   [(Alice, Sales), (Bob, Eng), (Carol, Sales), (Dave, Eng)]

Sort by department (stable): [(Bob, Eng), (Dave, Eng), (Alice, Sales), (Carol, Sales)] ↑ Eng group keeps Bob before Dave (original order) ✓ ↑ Sales group keeps Alice before Carol (original order) ✓

Sort by department (unstable — might produce): [(Dave, Eng), (Bob, Eng), (Carol, Sales), (Alice, Sales)] ↑ Original order within groups is lost ✗

Complexity Analysis

Metric Complexity Notes
Best-case time O(n log n) Always splits and merges — no shortcut for sorted input
Average-case time O(n log n) Same as best case
Worst-case time O(n log n) Same as best case — this is the big advantage
Space O(n) Needs a temporary array for merging
Stable? Yes Equal elements keep their relative order

The O(n log n) guarantee in all cases is what makes merge sort special. There are log2(n) levels of recursion, and each level does O(n) total work across all the merges. Multiply them together: n × log n.

The trade-off is O(n) extra space. Unlike in-place algorithms, merge sort needs a temporary buffer to hold the merged results. For large datasets, this memory overhead can matter.

Merge Sort vs. Insertion Sort

Merge SortInsertion Sort
Best case O(n log n) O(n) — nearly sorted input
Worst case O(n log n) O(n²) — reverse sorted
Space O(n) O(1) — in place
Stable? Yes Yes
Overhead Higher (recursion, allocation) Very low
Best for Large datasets, guaranteed performance Small arrays (n < 20–50), nearly sorted data

For small arrays, insertion sort's low overhead makes it faster despite the worse asymptotic complexity. That's why real-world implementations like Timsort use a hybrid approach: merge sort for the overall structure, insertion sort for small subarrays.

Where Merge Sort Is Used

Application Why merge sort?
External sorting When data doesn't fit in RAM, merge sort naturally works with chunks read from disk. Sort each chunk in memory, then merge the sorted chunks — this is exactly how database systems sort large tables.
Python's Timsort Python's built-in sorted() and list.sort() use Timsort, a hybrid of merge sort and insertion sort. Java's Arrays.sort() for objects uses the same approach.
Linked list sorting Merge sort is the algorithm of choice for linked lists. Unlike quicksort, it doesn't need random access — just pointer manipulation. And the merge step needs no extra space for linked lists.
Parallel sorting The two halves are independent, so they can be sorted on different cores or machines. MapReduce-style systems use this naturally.
Counting inversions A modified merge sort can count the number of inversions (out-of-order pairs) in O(n log n) — a useful measure of how "unsorted" a list is.

Key Takeaways

  • Merge sort splits the array in half, recursively sorts each half, then merges the sorted halves — the classic divide-and-conquer pattern
  • The merge step uses a two-pointer technique to combine two sorted arrays in O(n) time
  • Time complexity is O(n log n) in all cases — best, average, and worst — making it predictable and reliable
  • It requires O(n) extra space for the temporary merge buffer, which is the main trade-off
  • It's stable: equal elements maintain their original relative order
  • For small arrays, insertion sort is faster due to lower overhead — real-world sorts like Timsort combine both
  • Merge sort excels at external sorting (data on disk), linked lists, and parallel computation

Merge sort is the gateway to recursive thinking. Once you understand how splitting a problem in half and combining the results can yield an efficient algorithm, you'll see the same pattern everywhere — quicksort, binary search, FFT, and beyond. The divide-and-conquer paradigm is one of the most powerful ideas in all of computer science.