Algorithms · Sorting

Sorting algorithms

There is no universally best sorting algorithm. Key distribution, available memory, stability and input shape determine the right choice. Each card opens a visualizer for comparisons, movements and auxiliary structures.

Comparison table

AlgorithmBestAverageWorstAuxiliary memoryStableIn place
Insertion sort Θ(n)Θ(n²)Θ(n²)Θ(1) Yes Yes
Merge sort Θ(n log n)Θ(n log n)Θ(n log n)Θ(n) Yes No
Quicksort Θ(n log n)Θ(n log n)Θ(n²)Θ(log n)¹ No Yes
Heapsort Θ(n log n)Θ(n log n)Θ(n log n)Θ(1) No Yes
Counting sort Θ(n + k)Θ(n + k)Θ(n + k)Θ(n + k) Yes No
Radix sort (LSD) Θ(d(n + b))Θ(d(n + b))Θ(d(n + b))Θ(n + b) Yes No
Bucket sort Θ(n + k)Θ(n + k)²Θ(n²)Θ(n + k) Depends³ No

1 Average quicksort stack; it can become Θ(n) in the worst case. “In place” here allows the recursion stack.

2 With an approximately uniform distribution across k buckets and a suitable local sort.

3 Bucket sort is stable only when distribution, internal sorting and concatenation preserve equal-key order.

Parametri: n elements; k key range or bucket count; d digits; b numeric base.

Two families, two different limits

Comparison sorts

Insertion, merge, quick and heap sort decide order by comparing keys. In the general model they need Ω(n log n) worst-case comparisons.

Non-comparison sorts

Counting, radix and bucket sort exploit key structure. They can be linear in n, but their cost also depends on range, digits or distribution.

Open a visualizer

How to choose in practice

Small or nearly sorted inputInsertion sort
Guarantee and stabilityMerge sort
In-memory array, strong average caseQuicksort
Constant memory and guaranteeHeapsort
Integers in a small rangeCounting sort
Bounded-length integers or stringsRadix sort
Roughly uniformly distributed valuesBucket sort
Real libraries often use hybrids: insertion sort for small subproblems, introsort to limit quicksort’s worst case, or Timsort to exploit existing ordered runs.

Properties complexity alone does not capture

Stable
Equal-key elements keep their relative order. Essential for successive sorts by multiple fields.
In place
Uses constant or very small memory beyond the array; conventions about recursion stack must be stated.
Adaptive
Gets faster when the input is already partly sorted. Insertion sort is the classic example.
Online
Can maintain order as new elements arrive. Insertion sort supports this naturally.