Skip to main content

Beyond Quadratic Sorting

5 min readRead first: Quicksort

Quicksort is not the only way to sort faster than O(n2)O(n^2). This lesson presents Mergesort, which sorts by merging and guarantees O(nlog⁡n)O(n \log n) in every case, explains the theoretical limit that all comparison-based algorithms share, and shows what the sorting methods of real libraries use.

What you will learn in this lesson
  • Mergesort, which sorts by merging, guarantees O(nlog⁡n)O(n \log n) and is stable.
  • Why no algorithm based on comparisons can beat O(nlog⁡n)O(n \log n) 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:

  1. Divide the vector into two halves.
  2. Sort each half, recursively.
  3. 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)
}
}
Mergesort on 4 5 6 1 3 2 7 8: divide into halves, then merge sorted halves45613278456132784561327845613278451623781456237812345678dividebasemerge
Mergesort on 4 5 6 1 3 2 7 8. The vector is halved until the parts have one element, and then the sorted halves are merged level by level. There are log₂ 8 = 3 levels of merging, each costing O(n).

The recursion always divides the vector into halves, regardless of the data, so there are always about log⁡2n\log_2 n levels, each with a total merging cost of O(n)O(n). Mergesort is therefore O(nlog⁡n)O(n \log n) 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 nn, 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 n

The 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 O(nlog⁡n)O(n \log n)? 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 ai<aja_i \lt a_j?"), 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 n!n! leaves (one per permutation).
  • A binary tree of height hh has at most 2h2^h leaves, so 2h≥n!2^h \ge n!, that is, h≥log⁡2(n!)h \ge \log_2 (n!).
  • The height hh is the number of comparisons in the worst case, and log⁡2(n!)\log_2(n!) grows like nlog⁡2nn \log_2 n (more precisely, log⁡2(n!)≈nlog⁡2n−1.44 n\log_2(n!) \approx n \log_2 n - 1.44\,n).
Decision tree of insertion sort for three elements a, b, ca ≤ b?b ≤ c?yesa ≤ c?noa b cyesa ≤ c?nob a cyesb ≤ c?noa c byesc a bnob c ayesc b ano3! = 6 leaves, one per order · height 3 = comparisons in the worst case
The decision tree of insertion sort for three elements. Every comparison sort has such a tree; it needs one leaf per possible order (3! = 6), and its height is the number of comparisons in the worst case.

Every comparison-based sorting algorithm needs Ω(nlog⁡n)\Omega(n \log n) 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 O(nlog⁡n)O(n \log n) 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 1000!1000! leaves, so its height is at least ⌈log⁡2(1000!)⌉=8,530\lceil \log_2 (1000!) \rceil = 8{,}530. 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 O(nlog⁡n)O(n \log n) algorithm if the recursion gets too deep, with insertion sort for small parts; and std::stable_sort for a stable sort.

The lesson is that there is no single "best" sorting algorithm: each one has strengths, and good engineering combines them.

Common mistakes
  • Calling Quicksort stable. It is not; Mergesort is the stable O(nlog⁡n)O(n \log n) option.
  • Creating a new auxiliary array in every call of Mergesort. Allocate one array of size nn once and reuse it.

Summary​

AlgorithmBestAverageWorstExtra memoryStable
MergesortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n)O(n)Yes
QuicksortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n2)O(n^2)O(log⁡n)O(\log n) stackNo
  • Mergesort sorts by merging: O(nlog⁡n)O(n \log n) in every case and stable, at the price of O(n)O(n) extra memory.
  • No comparison-based algorithm can beat Ω(nlog⁡n)\Omega(n \log n) 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 ⌈log⁡2(n!)⌉\lceil \log_2 (n!) \rceil for n=3,4,5n = 3, 4, 5. Can you find an algorithm that sorts 4 elements with exactly that number of comparisons in the worst case?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.