AlgoLab

O(n log n)·O(n) space·stable
645559896316373459948511843281951114277

Starting merge sort on an array of 20 items.

Starting merge sort on an array of 20 items.
  1. 1if the range holds more than one value, split it at the middle
  2. 2recursively sort the left half
  3. 3recursively sort the right half
  4. 4compare the next unmerged value from each half
  5. 5write the smaller of the two into the array and advance that half
  6. 6copy any values left over in one half back into the array
  7. 7the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n log n)
AverageO(n log n)
WorstO(n log n)
Extra spaceO(n)
StableYes
n log₂ n at n=20 predicts 86; this run took 0.

Merge sort

Merge sort splits the array in half recursively until each piece holds at most one value, then merges pairs of sorted halves back together by repeatedly taking the smaller of the two next unmerged values.

When it is the right choice

Merge sort is the right choice when predictable O(n log n) performance matters more than memory use, and when stability is required — for instance sorting records by a secondary key after already sorting them by a primary one. Its downside is that merging needs O(n) auxiliary space, unlike quicksort's in-place partitioning, so it is a weaker choice under tight memory constraints.

How it works

Worth noticing

Cost

Best
O(n log n)
Average
O(n log n)
Worst
O(n log n)
Extra space
O(n)
Stable
Yes

Worth comparing

All algorithms