Choosing the right sort
No single sorting algorithm wins everywhere — the right choice depends on data size, distribution, memory limits and whether you need stability. This reference puts the common algorithms side by side with their best, average and worst-case time complexity, space cost and stability, so you can pick deliberately. Search by keyword or sort the table by any complexity column.
How it works
Algorithms split into comparison sorts and non-comparison sorts:
Comparison sorts (≥ O(n log n) worst case):
Quick avg O(n log n), worst O(n²), in-place, unstable
Merge O(n log n) always, stable, needs O(n) extra space
Heap O(n log n) always, in-place O(1), unstable
Timsort O(n) best, O(n log n) avg, stable (Python/Java default)
Non-comparison sorts (linear, bounded keys):
Counting O(n + k) Radix O(d(n + k)) Bucket O(n + k) avg
Comparison sorts have a proven O(n log n) lower bound because they must distinguish all n! orderings. Non-comparison sorts beat it by exploiting integer key structure, trading memory and generality for speed.
Tips and example
- For general-purpose array sorting, a tuned quicksort (randomised or median-of- three pivot) is usually fastest; standard libraries often use Timsort or introsort under the hood.
- Need stability or worst-case guarantees? Use mergesort or Timsort.
- Sorting nearly-sorted data? Insertion sort and Timsort approach O(n).
- Tight on memory with a worst-case guarantee required? Heapsort sorts in place in O(1) extra space, at the cost of cache locality and stability.