Beyond Quadratic Sorting
Quicksort is not the only way to sort faster than . This lesson presents Mergesort, which sorts by merging and guarantees in every case, explains the theoretical limit that all comparison-based algorithms share, and shows what the sorting methods of real libraries use.
- Mergesort, which sorts by merging, guarantees and is stable.
- Why no algorithm based on comparisons can beat in the worst case.
- What the sorting methods of real libraries use.
Mergesort: Sorting by Merging
Mergesort is based on a different idea: merging two sorted sequences into a single sorted sequence is easy and fast, since it only requires comparing the first elements of both and taking the smaller one, repeatedly. So:
- Divide the vector into two halves.
- Sort each half, recursively.
- Merge the two sorted halves.
private void mergeSort(int[] elements, int[] aux, int left, int right) {
if (left < right) {
int center = left + (right - left) / 2;
mergeSort(elements, aux, left, center);
mergeSort(elements, aux, center + 1, right);
merge(elements, aux, left, center, right); // linear in (right - left + 1)
}
}
The recursion always divides the vector into halves, regardless of the data, so there are always about levels, each with a total merging cost of . Mergesort is therefore in all cases, and, unlike Quicksort, it is stable (when the two candidates are equal, the merge takes the one from the left half). Its drawback is memory: merging arrays requires an auxiliary array of size , so it is not in place.
Mergesort is a classic example of divide and conquer, and you will study it in detail (with its recurrence, its variants and its applications) in that chapter. It is also the basis of external sorting algorithms (see the next lesson) and of TimSort, the algorithm used by Java to sort objects and by Python to sort lists.
ProofMergesort is correct and costs n log nThe Limit of Comparison-Based Sorting
All the algorithms we have seen so far sort by comparing pairs of elements. Can such an algorithm be faster than ? The answer is no, and the argument is one of the most elegant results in computer science.
Any comparison-based algorithm can be represented as a decision tree: each internal node is a comparison ("is ?"), and the two branches correspond to its two possible outcomes. Each leaf is a final arrangement of the input. Then:
- To sort correctly, the algorithm must be able to produce every possible order of the input, so the tree needs at least leaves (one per permutation).
- A binary tree of height has at most leaves, so , that is, .
- The height is the number of comparisons in the worst case, and grows like (more precisely, ).
Every comparison-based sorting algorithm needs comparisons in the worst case.
This is a statement about the problem, not about a particular algorithm: no one will ever find a comparison-based algorithm that does better. Mergesort, which is in the worst case, is therefore asymptotically optimal.
ProofNo comparison sort can beat n log n🧠 Checkpoint: How many comparisons at least?
Question: Can a comparison-based algorithm sort any array of 1,000 elements with at most 8,000 comparisons?
Answer: No. The decision tree needs at least leaves, so its height is at least . Some input will always need at least 8,530 comparisons, whatever the algorithm.
What Real Libraries Use
Real sorting libraries combine several algorithms to get the best of each:
- Java, primitive types (
Arrays.sort(int[]), etc.): a dual-pivot Quicksort, with insertion sort for small parts. Stability does not matter for primitives, and Quicksort is the fastest in practice. - Java, objects (
Arrays.sort(Object[]),Collections.sort,List.sort): TimSort, a hybrid of Mergesort and insertion sort that detects already sorted runs in the data. It is stable, which is essential for objects, and very fast on partially sorted data. - Python (
sorted,list.sort): TimSort as well (it was designed for Python). - C++ (
std::sort): typically Introsort, a Quicksort that switches to another algorithm if the recursion gets too deep, with insertion sort for small parts; andstd::stable_sortfor a stable sort.
The lesson is that there is no single "best" sorting algorithm: each one has strengths, and good engineering combines them.
- Calling Quicksort stable. It is not; Mergesort is the stable option.
- Creating a new auxiliary array in every call of Mergesort. Allocate one array of size once and reuse it.
Summary
| Algorithm | Best | Average | Worst | Extra memory | Stable |
|---|---|---|---|---|---|
| Mergesort | Yes | ||||
| Quicksort | stack | No |
- Mergesort sorts by merging: in every case and stable, at the price of extra memory.
- No comparison-based algorithm can beat comparisons in the worst case; Mergesort reaches that limit.
- Real libraries combine several algorithms: dual-pivot Quicksort for primitives and TimSort (Mergesort + insertion) for objects in Java.
Practice
- ✍️ Trace Mergesort. Sort 5 6 1 3 9 8 7 4 2 with Mergesort, writing the two halves and the result of each merge.
- 💻 Run it. The course repository contains
Mergesort. Measure it with sorted, random and reverse data and compare it with Quicksort. Which one is more predictable? - 🧮 The lower bound. Compute for . Can you find an algorithm that sorts 4 elements with exactly that number of comparisons in the worst case?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.