Merge Sort
- Ω( n log n )
- Θ( n log n )
- O( n log n )
- space O( n )
Merge sort splits the array until single elements remain, then rebuilds sorted runs by merging neighbours. Its merge step copies a range into an auxiliary buffer and writes the winners back into the original array, always preferring the left element on a tie. That tie rule makes it stable, and the buffer is the price: extra memory proportional to the array.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How merge sort works
The recursion always splits at the midpoint, so the six elements become 5, 2, 6 and 1, 4, 3, then 5, 2 and 6 on the left, and 1, 4 and 3 on the right. The first real merge handles 5 and 2. Both are copied into the buffer, the 2 wins, and the array reads 2, 5, 6, 1, 4, 3 after two writes. Merging that run with the lone 6 rewrites the 2 and the 5 in the same places, so the next two rows of the table show no visible change. The 6 is the leftover element of the right run and is never written again.
The right half goes the same way. Merging 1 and 4 writes the 1 back at index 3 and needs nothing more, because the 4 is the right-hand leftover and already sits in place. Merging the run 1, 4 with the 3 writes the 1 again, then the 3 into index 4 and the 4 into index 5, giving 2, 5, 6, 1, 3, 4. After 8 writes both halves are sorted: 2, 5, 6 and 1, 3, 4.
The final merge copies all six values into the buffer and writes six results. It takes the 1 from the right half, the 2 from the left, then the 3 and the 4 from the right. Once the right run is used up, the remaining 5 and 6 are copied from the buffer into indexes 4 and 5. In total the sort makes 10 comparisons, 14 writes to the array and 16 writes to the buffer, and the counters list the two kinds of memory separately.
| Step | Change | Array after |
|---|---|---|
| 1 | Write 2 at index 0 | 2 2 6 1 4 3 |
| 2 | Write 5 at index 1 | 2 5 6 1 4 3 |
| 3 | Write 2 at index 0 | 2 5 6 1 4 3 |
| 4 | Write 5 at index 1 | 2 5 6 1 4 3 |
| 5 | Write 1 at index 3 | 2 5 6 1 4 3 |
| 6 | Write 1 at index 3 | 2 5 6 1 4 3 |
| 7 | Write 3 at index 4 | 2 5 6 1 3 3 |
| 8 | Write 4 at index 5 | 2 5 6 1 3 4 |
| 9 | Write 1 at index 0 | 1 5 6 1 3 4 |
| 10 | Write 2 at index 1 | 1 2 6 1 3 4 |
| 11 | Write 3 at index 2 | 1 2 3 1 3 4 |
| 12 | Write 4 at index 3 | 1 2 3 4 3 4 |
12 of 14 changes shown; the rest follow the same pattern until the array is sorted.
Pseudocode
mergesort(lo, hi)
if hi - lo < 2
return
mid = (lo + hi) / 2
mergesort(lo, mid)
mergesort(mid, hi)
copy a[lo .. hi - 1] to buffer
i = lo, j = mid, k = lo
while i < mid and j < hi
if buffer[j] < buffer[i]
a[k] = buffer[j], j = j + 1
else
a[k] = buffer[i], i = i + 1
k = k + 1
copy the rest of either half into a[k ...]
Why these complexities
Every level of the recursion touches all n elements once, and there are about log₂ n levels, because each split halves the range. A merge of two runs with m elements between them always copies m values into the buffer and writes at most m back, so the work per level is linear whatever the data looks like. That is why best, average and worst are all n log n.
The cases differ only in the constant. On sorted input every merge ends as soon as the left run is used up, after about m/2 comparisons, which is half the worst case. When the two runs interleave perfectly, a merge needs close to m − 1 comparisons. The copy into the buffer is unconditional, so the total time stays n log n either way. This implementation does not look for runs that already exist, which is why it is not adaptive.
Space is n for the buffer, allocated once and shared by every merge, plus about log n stack frames for the recursion. Stability comes from one strict comparison: the right element is taken only when it is strictly smaller than the left one, so equal elements keep their order. Merging two runs through a buffer is cheap on arrays, while merging in place is awkward and slow, which is why the sort is listed as not in place.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 123 | 305 | 0 |
| Already sorted | 80 | 240 | 0 |
| Reversed | 80 | 320 | 0 |
| Few distinct values | 114 | 292 | 0 |
When to use it
Use it when you need a predictable O(n log n) time and a stable result, for example to sort records by several keys in turn. It is also the natural choice for linked lists and for data that does not fit in memory. The price is an auxiliary buffer.
Frequently asked questions
Is merge sort stable?
Yes. When two front elements are equal the merge takes the one from the left half first.
How much extra memory does it need?
An auxiliary buffer the size of the array, so O(n) space.
Is merge sort faster than quick sort?
It has a better worst case, but quick sort is usually faster on arrays because it works in place. Merge sort is stronger on linked lists.
Why does the merge skip writing the leftover right run?
When the left run is used up first, the elements still waiting on the right already stand at the end of the range in sorted order, because the merge writes into the same positions it started from. Copying them would only repeat a write that changes nothing. When the right run runs out first, the left leftovers do have to be moved to the end of the range, and the code writes them back from the buffer.
Why are there two sets of read and write counters?
The array being sorted and the helper buffer are counted separately. On the six-value trace the array sees 16 reads and 14 writes, and the buffer 24 reads and 16 writes. Merge sort moves more data than its 10 comparisons suggest, since every merge copies the whole range into the buffer before it compares anything.
Background
John von Neumann is generally credited with the method. He described a merge sort in 1945, and Knuth counts it among the first sorting methods ever worked out for a stored-program computer. Merging suited the machines of the time well, because sorted runs could be streamed from tape and combined with purely sequential reads.
The same idea scales from memory to disk, which is why database engines still sort huge tables by producing sorted runs and merging them. Many standard library sorts for objects descend from it: Python's list sort and Java's object sort use Timsort, a merge sort that detects runs already present in the data and merges those. The top-down recursion used here and the bottom-up version that merges runs of size 1, 2, 4 and so on have the same n log n cost. Knuth's section 5.2.4 develops the bottom-up form.
References
- Knuth, The Art of Computer Programming, vol. 3, section 5.2.4 (Sorting by Merging)
- Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, section 2.3 (Designing algorithms)
- Sedgewick, Wayne, Algorithms, 4th edition, section 2.2 (Mergesort)
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Bitonic Sort | Θ( n log2 n ) | O( n log2 n ) |
| Best time | Ω( n log n ) | good |
|---|---|---|
| Average time | Θ( n log n ) | good |
| Worst time | O( n log n ) | good |
| Worst space | O( n ) | fair |
Properties
- Stable
- Yes
- In place
- No
- Adaptive
- No
- Comparison-based
- Yes