How mergesort keeps a stable n log n bound

Short answer: Mergesort splits the array in half, sorts each half, and merges with two pointers. Ties take the left element, so equal keys keep their original order. Every level does Θ(n) work and there are Θ(log n) levels, which fixes the worst case at Θ(n log n) comparisons. The merge writes into an auxiliary buffer the size of the input.


What the problem actually asks

The input is a sequence under a total order. A stable result means that if two keys compare equal, the one that appeared earlier still appears earlier after sorting. The cost has to be stated for the worst input, because a bound that holds only on random data leaves a caller who must meet a deadline without a number.

The merge step is the whole algorithm. Two sorted runs become one sorted run by walking a pointer down each run and always emitting the smaller head. When the heads are equal, the left run’s head is emitted. That rule is the stability proof.


What the algorithm guarantees

A top-down split yields about log₂ n levels. Each level copies every element a constant number of times, so the comparison and move counts are both Θ(n log n) on every input, including a sorted one and a reversed one. The auxiliary buffer is Θ(n). Recursion depth is Θ(log n). Bottom-up mergesort performs the same merges iteratively, doubling the run width each pass, and uses the same buffer.

On a linked list the same merges can be done by rewiring pointers. A bottom-up list mergesort then needs only a handful of node pointers beyond the list itself. The comparison bound stays Θ(n log n).


The working steps

  1. If the slice has fewer than two elements, it is already sorted.
  2. Split at the midpoint. Sort the left half, then the right half.
  3. Merge by comparing the two heads. On a tie, take the left head.
  4. Copy the merge back over the slice, or alternate buffers so the next level reads the buffer just written.
  5. Repeat until one run covers the array. Bottom-up code skips the recursion and doubles the run width each pass.

The bound is a comparison bound on a random-access sequence or a linked list. A file larger than memory, whose cost is measured in passes over disk, is external mergesort. That algorithm keeps the merge and changes the accounting.


Approaches that look simpler and fail

Approach Why it fails when a stable n log n sort is required
Insertion sort on the whole array The worst case is Θ(n²) moves. A long reversed run misses a deadline that n log n was chosen to meet.
Quicksort with a random pivot The expected cost is O(n log n), and a bad pivot sequence is Θ(n²). A typical partition also moves equal keys past each other.
Heapsort The worst case is O(n log n) and the sort is in place. Extracting the heap root reorders equal keys.
Copy the left run and then the right run Concatenation is sorted only when every left key is already at most every right key. Overlapping key ranges need the two-pointer merge.

An in-place O(n log n) comparison sort is heapsort. Adaptive sorting of naturally ordered runs is timsort, which still merges and adds a run stack on top of this merge.


A working example

The Bash script and the Python script stable-merge the same integers. A tie takes the left item. Both print 1 1 2 3 4. The Python check also keeps the original indexes, so the two equal keys stay in the order they arrived.

a=(3 1 4 1 2)
mergesort() {
  local lo=$1 hi=$2 mid i j k
  local -a tmp
  if (( hi - lo < 2 )); then return; fi
  mid=$(( (lo + hi) / 2 ))
  mergesort "$lo" "$mid"
  mergesort "$mid" "$hi"
  i=$lo; j=$mid; k=0
  while (( i < mid && j < hi )); do
    if (( a[i] <= a[j] )); then tmp[k]=${a[i]}; i=$((i+1))
    else tmp[k]=${a[j]}; j=$((j+1)); fi
    k=$((k+1))
  done
  while (( i < mid )); do tmp[k]=${a[i]}; i=$((i+1)); k=$((k+1)); done
  while (( j < hi )); do tmp[k]=${a[j]}; j=$((j+1)); k=$((k+1)); done
  for ((i=0; i<k; i++)); do a[lo+i]=${tmp[i]}; done
}
mergesort 0 ${#a[@]}
echo "${a[*]}"
def mergesort(a):
    if len(a) < 2:
        return a
    mid = len(a) // 2
    left, right = mergesort(a[:mid]), mergesort(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i][0] <= right[j][0]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

pairs = mergesort([(3, 0), (1, 1), (4, 2), (1, 3), (2, 4)])
assert pairs == [(1, 1), (1, 3), (2, 4), (3, 0), (4, 2)]
print(*(v for v, _ in pairs))

Where it is used

Timsort, the stable sort in CPython and in Java’s sort of objects, merges natural runs. A plain mergesort is also how a database or sort orders a file that does not fit in memory. Stability is why equal keys keep the order a later pass depends on.


When you can drop this algorithm

Drop mergesort when the auxiliary buffer cannot be allocated and stability can be given up. Heapsort and introsort then provide an O(n log n) worst case in place. Drop it on a short array, where insertion sort does fewer moves. Keep mergesort when the result must be stable and the worst-case comparison count must be n log n.


Why this stays published

We publish this so a search for mergesort returns the stable merge rule and the buffer that pays for the worst-case bound. Mergesort is the stable comparison sort whose cost is n log n on every input, paid for with a linear auxiliary buffer.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *