Sorting in brief
Sorting arranges elements in an order defined by a comparison, such as ascending numbers or alphabetical strings. It underpins searching (binary search needs sorted input), database operations such as joins and grouping, and many divide-and-conquer algorithms. Algorithms are judged by running time, extra memory, whether they are stable (equal elements keep their original order) and whether they sort in place (Cormen et al., 2022).
There is a distinction between internal sorting, where all data fit in main memory, from external sorting, where data are too large and are sorted in chunks on disk and then merged. Merge sort is the basis of most external sorting, but it is also a standard in-memory algorithm. Modern work adds a third setting, parallel sorting on multicore machines, which has its own models and trade-offs (Sanders et al., 2019).

The classic algorithms compared
| Algorithm | Idea | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|---|
| Bubble sort | Repeatedly swap adjacent out-of-order pairs | O(n) with an early-exit check | O(n2) | O(n2) | O(1) | Yes |
| Selection sort | Select the minimum of the unsorted part and move it to the front | O(n2) | O(n2) | O(n2) | O(1) | No (usual array form) |
| Insertion sort | Insert each element into the sorted prefix | O(n) | O(n2) | O(n2) | O(1) | Yes |
| Merge sort | Sort halves recursively, then merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort | Partition around a pivot, then sort each side | O(n log n) | O(n log n) | O(n2) | O(log n) stack if the smaller side is recursed first | No |
| Heap sort | Build a heap, repeatedly extract the maximum | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
All comparison sorts need Ω(n log n) comparisons in the worst case (Cormen et al., 2022), so merge sort and heap sort are asymptotically optimal. The quadratic algorithms still matter: insertion sort is fast on small or nearly sorted arrays because its inner loop is short and cache friendly, which is why library sorts commonly switch to it for small ranges. Bounds describe growth, not speed on a given machine; the constants they hide are exactly what a benchmark measures.
Implementing two of them in C++
Insertion sort
- template <typename T> void insertion_sort(std::vector<T>& a) {
- for (std::size_t i = 1; i < a.size(); ++i) {
- T key = std::move(a[i]); std::size_t j = i;
- while (j > 0 && key < a[j - 1]) { a[j] = std::move(a[j - 1]); --j; }
- a[j] = std::move(key); } }
The loop compares with a[j - 1] and stops at j > 0, which avoids the most common bug: decrementing an unsigned index below zero, which wraps to a huge value instead of becoming negative. Using strict "less than" keeps the sort stable.
Quicksort with a median-of-three pivot
- If the range has fewer than about 16 elements, sort it with insertion sort and return.
- Choose the pivot as the median of the first, middle and last elements; compute the middle as lo + (hi - lo) / 2 to avoid overflow.
- Partition so that elements smaller than the pivot come first; with many duplicate keys, use a three-way partition (less, equal, greater) so equal keys are not re-sorted.
- Recurse on the smaller part and loop on the larger part, which bounds the stack depth by O(log n).
Each step answers a known failure. A first- or last-element pivot gives quadratic time on sorted or reverse sorted input; naive recursion on the larger side can overflow the stack on large arrays; and two-way partitioning degrades when most keys are equal (Cormen et al., 2022).
Difficulties you will meet in coding
- Off-by-one and unsigned indices. Mixing int and std::size_t, or loops that run to i <= n, read past the end of the array. Test empty, one-element and two-element inputs first.
- Comparator errors. std::sort requires a comparator that defines a strict weak ordering. A comparator written with <=, or one that is inconsistent for equal values, gives undefined behaviour, which can mean wrong output or a crash.
- Stability assumptions. std::sort is not stable. If equal keys must keep their order, as when sorting records by a second field, use std::stable_sort.
- Copies instead of moves. Sorting large objects by copying is slow; move elements, or sort indices or pointers instead.
- Testing only random input. Many bugs and slowdowns appear only on sorted, reverse sorted or duplicate-heavy inputs. Check every output with std::is_sorted and, for stable sorts, against a reference result.
In most research code, the right choice is std::sort or std::stable_sort, which are engineered for typical inputs. Implementing your own algorithm is justified when the algorithm is your research object, or when a measured property of your data, such as small integer keys, suggests a specialised method.
Benchmarking: what to measure
Algorithm engineering treats design, analysis, implementation and experiment as one cycle, with experiments used to test hypotheses about performance rather than to decorate a result (Sanders, 2009; Mendling et al., 2026). For sorting this means deciding before you run anything which question the experiment answers, for example "at what input size does my quicksort overtake insertion sort on nearly sorted data?" (McGeoch, 2012).
| Element | What to report |
|---|---|
| Inputs | Sizes over several orders of magnitude; distributions (random, sorted, reverse, few unique keys, nearly sorted); data types; random seeds |
| Baselines | std::sort and std::stable_sort on the same inputs |
| Measures | Wall-clock time from a monotonic clock; also comparisons and moves where theory predicts them |
| Repetition | Warm-up runs, number of repetitions, and summary statistics such as the median with an interval |
| Environment | CPU model, memory, operating system, compiler and version, optimisation flags |
| Isolation | Steps taken to limit interference from other processes and frequency scaling |
| Artefacts | Code, scripts and raw timings, with a version identifier |
Measurement is harder than it looks. Beyer et al. (2019) showed that common timing methods can miss resource use and that shared hardware changes results, and built tools that isolate runs. At a larger scale, Axtmann et al. (2022) evaluated 21 sorting codes on 6 data types, 10 input distributions, 4 machines and 4 memory allocation strategies, with input sizes spanning 7 orders of magnitude, and found that many competitors performed worse than their own published benchmarks suggested. The lesson for a thesis is to limit claims to the inputs and machines you tested.
Worked example: a small benchmark design (illustrative)
A hypothetical master's project compares insertion sort, the quicksort above and std::sort on 32-bit integers. Sizes run from 10 to 10 million in powers of ten; each size is tested on random, sorted, reverse sorted, nearly sorted (1% of elements displaced) and few-unique (ten distinct keys) inputs, each generated from a recorded seed. Every configuration is run 30 times after three warm-up runs, and the median and interquartile range are reported. Insertion sort is skipped above 100,000 elements on random input, where its quadratic cost makes runs impractical, and this is stated. Times are plotted divided by n log n, so that a flat line indicates the expected growth. The code, scripts, compiler version and flags are published with the thesis (Sandve et al., 2013; Peng, 2011). No results are given here; the design is the point.
Common mistakes
- Reporting a single run, or the fastest of several runs, as the result.
- Benchmarking unoptimised debug builds.
- Testing only random inputs, which hides the worst cases of simple pivot rules.
- Comparing a custom sort with no standard library baseline.
- Claiming general superiority from one machine and one data type (Axtmann et al., 2022).
- Not checking that outputs are actually sorted.
For benchmarking stochastic algorithms, see how to choose and benchmark a metaheuristic for your thesis.
Key takeaways
- Compare sorts by worst, average and best case, extra space and stability, not by one number (Cormen et al., 2022).
- Most C++ sorting bugs come from unsigned indices, invalid comparators and untested edge cases.
- Use std::sort or std::stable_sort unless your research question needs a custom algorithm.
- Design benchmarks as experiments: defined questions, varied inputs, repetitions and baselines (McGeoch, 2012; Sanders, 2009).
- Report the environment and publish code and raw timings so that others can reproduce the results (Beyer et al., 2019; Sandve et al., 2013).
