Blog articleMethodology & analyticsComputer science

Implementing and benchmarking sorting algorithms in C++: what to measure and report

Sorting algorithms are simple to describe and surprisingly easy to get wrong in code. This article compares the classic algorithms, shows where C++ implementations usually fail, and explains how to benchmark them so that performance claims in a thesis or paper can be trusted.

What you will learn

  • Compare bubble, selection, insertion, merge, quick and heap sort by time, space and stability
  • Implement insertion sort and quicksort in C++ while avoiding the usual indexing and recursion errors
  • Use the standard library sorts correctly, including comparator requirements
  • Design a benchmark with controlled inputs, repetitions and a fair baseline
  • Report sorting experiments so that others can reproduce them

What you will unlearn

  • Big-O tells you which algorithm is faster on your data.Asymptotic bounds ignore constants and input structure, so measured performance must be tested on realistic inputs.
  • Quicksort is always O(n log n).Its average case is O(n log n), but a poor pivot rule gives O(n2) on inputs such as already sorted arrays.
  • One timing run is enough.Run times vary with caches, other processes and frequency scaling, so repeated, controlled runs are needed.
  • Writing your own sort is the best way to get speed.The standard library sorts are heavily engineered; a custom sort needs a measured reason to exist.

Skills you will practise

  • Complexity analysis
  • C++ implementation
  • Debugging edge cases
  • Benchmark design
  • Performance reporting
  • Reproducible code

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).

Sorting algorithms in C++
Figure 1. Illustration on sorting algorithms in C++.

The classic algorithms compared

Time, space and stability of comparison sorts (n elements)
AlgorithmIdeaBestAverageWorstExtra spaceStable
Bubble sortRepeatedly swap adjacent out-of-order pairsO(n) with an early-exit checkO(n2)O(n2)O(1)Yes
Selection sortSelect the minimum of the unsorted part and move it to the frontO(n2)O(n2)O(n2)O(1)No (usual array form)
Insertion sortInsert each element into the sorted prefixO(n)O(n2)O(n2)O(1)Yes
Merge sortSort halves recursively, then mergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuicksortPartition around a pivot, then sort each sideO(n log n)O(n log n)O(n2)O(log n) stack if the smaller side is recursed firstNo
Heap sortBuild a heap, repeatedly extract the maximumO(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

  1. template <typename T> void insertion_sort(std::vector<T>& a) {
  2. for (std::size_t i = 1; i < a.size(); ++i) {
  3. T key = std::move(a[i]); std::size_t j = i;
  4. while (j > 0 && key < a[j - 1]) { a[j] = std::move(a[j - 1]); --j; }
  5. 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

  1. If the range has fewer than about 16 elements, sort it with insertion sort and return.
  2. Choose the pivot as the median of the first, middle and last elements; compute the middle as lo + (hi - lo) / 2 to avoid overflow.
  3. 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.
  4. 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).

What to report in a sorting benchmark
ElementWhat to report
InputsSizes over several orders of magnitude; distributions (random, sorted, reverse, few unique keys, nearly sorted); data types; random seeds
Baselinesstd::sort and std::stable_sort on the same inputs
MeasuresWall-clock time from a monotonic clock; also comparisons and moves where theory predicts them
RepetitionWarm-up runs, number of repetitions, and summary statistics such as the median with an interval
EnvironmentCPU model, memory, operating system, compiler and version, optimisation flags
IsolationSteps taken to limit interference from other processes and frequency scaling
ArtefactsCode, 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).
Your next step

Want to apply this to your own study?

  1. 1Tell us your topic, data and deadline
  2. 2A statistician reviews your work with you
  3. 3You get a plan and a quote
Quantitative analysis

References

  1. Axtmann, M., Witt, S., Ferizovic, D., & Sanders, P. (2022). Engineering in-place (shared-memory) sorting algorithms. ACM Transactions on Parallel Computing, 9(1), 1–62. https://doi.org/10.1145/3505286
  2. Beyer, D., Löwe, S., & Wendler, P. (2019). Reliable benchmarking: Requirements and solutions. International Journal on Software Tools for Technology Transfer, 21(1), 1–29. https://doi.org/10.1007/s10009-017-0469-y
  3. Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to algorithms (4th ed.). MIT Press.
  4. McGeoch, C. C. (2012). A guide to experimental algorithmics. Cambridge University Press. https://doi.org/10.1017/CBO9780511843747
  5. Mendling, J., Leopold, H., Meyerhenke, H., & Depaire, B. (2026). Methodology of algorithm engineering. ACM Computing Surveys, 58(4), 1–38. https://doi.org/10.1145/3769071
  6. Peng, R. D. (2011). Reproducible research in computational science. Science, 334(6060), 1226–1227. https://doi.org/10.1126/science.1213847
  7. Sanders, P. (2009). Algorithm engineering: An attempt at a definition. In S. Albers, H. Alt, & S. Näher (Eds.), Efficient algorithms (Lecture Notes in Computer Science, Vol. 5760, pp. 321–340). Springer. https://doi.org/10.1007/978-3-642-03456-5_22
  8. Sanders, P., Mehlhorn, K., Dietzfelbinger, M., & Dementiev, R. (2019). Sequential and parallel algorithms and data structures: The basic toolbox. Springer. https://doi.org/10.1007/978-3-030-25209-0
  9. Sandve, G. K., Nekrutenko, A., Taylor, J., & Hovig, E. (2013). Ten simple rules for reproducible computational research. PLoS Computational Biology, 9(10), e1003285. https://doi.org/10.1371/journal.pcbi.1003285

How to cite this article

Choose your referencing style, then copy. Check your university's or journal's guide for local variations.

PhD Research Lab Academy. (2022, January 18). Implementing and benchmarking sorting algorithms in C++: what to measure and report. PhD Research Lab. https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it/

PhD Research Lab Academy. “Implementing and Benchmarking Sorting Algorithms in C++: What to Measure and Report.” PhD Research Lab, 18 Jan. 2022, www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it. Accessed [access date].

PhD Research Lab Academy (2022) Implementing and benchmarking sorting algorithms in C++: what to measure and report. PhD Research Lab. Available at: https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it/ (Accessed: [access date]).

PhD Research Lab Academy. “Implementing and Benchmarking Sorting Algorithms in C++: What to Measure and Report.” PhD Research Lab. January 18, 2022. https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it.

PhD Research Lab Academy, ‘Implementing and Benchmarking Sorting Algorithms in C++: What to Measure and Report’ (PhD Research Lab, 18 January 2022) <https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it> accessed [access date].

PhD Research Lab Academy. Implementing and benchmarking sorting algorithms in C++: what to measure and report [Internet]. PhD Research Lab; 2022 Jan 18 [cited [access date]]. Available from: https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it/

PhD Research Lab Academy, “Implementing and benchmarking sorting algorithms in C++: what to measure and report,” PhD Research Lab, Jan. 18, 2022. [Online]. Available: https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it. [Accessed: [access date]].

@online{how_to_implement_sorting_algorithms_in_c_and_difficulty_faced_in_coding_it_2022,
  author = {{PhD Research Lab Academy}},
  title = {{Implementing and benchmarking sorting algorithms in C++: what to measure and report}},
  organization = {PhD Research Lab},
  date = {2022-01-18},
  url = {https://www.phdassistance.com/blog/how-to-implement-sorting-algorithms-in-c-and-difficulty-faced-in-coding-it},
  urldate = {[access date]}
}

This article is for learning. Use it to understand the method and cite the original sources above in your own work; do not copy or submit it as your own.

Implementing and benchmarking sorting algorithms in C++Need help applying it to your study?
Quantitative analysis