Sorting Algorithms Compared: Time, Space and Stability
Every sorting algorithm puts the same items in the same order, so the differences are all in cost and behavior: how the time grows, how much extra memory it needs, what happens to equal keys, and how it reacts to input that is already partly sorted. This page puts the common sorts in one table, states the assumption behind each entry, and explains the two ideas that the table depends on, stability and the comparison lower bound. Examples use Python 3.10 or later and only the standard library.
The table
Here n is the number of items. For counting and radix sort, k is the size of the key range (or the base) and d the number of digits.
| Algorithm | Best | Average | Worst | Extra space | Stable | In place |
|---|---|---|---|---|---|---|
| Bubble sort | O(n) (1) | O(n^2) | O(n^2) | O(1) | Yes | Yes |
| Selection sort | O(n^2) | O(n^2) | O(n^2) | O(1) | No (2) | Yes |
| Insertion sort | O(n) | O(n^2) | O(n^2) | O(1) | Yes | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) (3) | Yes | No |
| Quicksort | O(n log n) | O(n log n) | O(n^2) | O(log n) (4) | No | Yes |
| Heap sort | O(n log n) (5) | O(n log n) | O(n log n) | O(1) | No | Yes |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes (6) | No |
| Radix sort (LSD) | O(d(n + k)) | O(d(n + k)) | O(d(n + k)) | O(n + k) | Yes | No |
The assumptions behind the numbered entries:
- Bubble sort's O(n) best case, on input that is already sorted, needs the early-exit check: stop when a full pass makes no swaps. Without it, bubble sort is O(n^2) on every input.
- Selection sort in its usual array form swaps items over long distances, which can reorder equal keys. A version that shifts items instead of swapping is stable but does more writes.
- Merge sort's O(n) extra space is for arrays (the merge needs a buffer). Merge sort on a linked list can relink nodes and needs no buffer.
- Quicksort's O(log n) space is the typical recursion depth. With consistently bad pivots the depth reaches O(n); recursing into the smaller part first and looping on the larger part keeps the depth at O(log n) in every case. Quicksort's O(n^2) worst case happens, for example, when the pivot is always the first item and the input is already sorted.
- Heap sort's O(n log n) best case assumes distinct keys. If every key is equal, each sift-down stops immediately and it finishes in O(n).
- Counting sort is stable in its usual form, which places items using prefix sums of the counts. That stability is what lets radix sort use it as its inner step.
The Algorithm Comparison Tool covers four of these sorts (bubble, merge, quick and heap) alongside linear search, binary search, BFS and DFS, and evaluates each class at an n you choose. At n = 1000 in the average case it gives merge, quick and heap sort 9,965.78 (that is n log2 n) and bubble sort 1,000,000 (n^2); switching to the worst case moves quicksort up to 1,000,000 beside bubble sort. Those are values of the growth functions, not timings: two algorithms in the same class can differ a lot in speed because of constant factors and memory access patterns.
Stability, with a two-key example
A sort is stable if items with equal keys keep the relative order they had before sorting. That sounds like a detail until you sort by more than one field. To list students by grade, and by name within each grade, you can sort by name first and then sort by grade with a stable sort: the second sort keeps the name order inside each grade.
students = [("Dana", "B"), ("Ali", "A"), ("Chen", "B"),
("Bea", "A"), ("Eve", "B")]
by_name = sorted(students) # first pass: by name
by_grade = sorted(by_name, key=lambda s: s[1]) # second pass: by grade
for name, grade in by_grade:
print(grade, name)
A Ali
A Bea
B Chen
B Dana
B Eve
Python's sorted() and list.sort() are guaranteed to be stable (the Python Sorting HOWTO states it), which is why this works. In practice you would write key=lambda s: (s[1], s[0]) and sort once, but the two-pass form shows what stability buys, and it is a simple way to sort by several keys in different directions, for example grade ascending but name descending, when a key such as a string cannot be negated.
An unstable sort can break the order. A plain selection sort, which swaps the minimum into place, moves the first B card behind the second one; the built-in sort keeps them as they were:
def selection_sort(a, key):
a = list(a)
for i in range(len(a)):
m = min(range(i, len(a)), key=lambda j: key(a[j]))
a[i], a[m] = a[m], a[i] # a long-distance swap
return a
cards = [("B", 1), ("B", 2), ("A", 3)] # two cards share the letter B
print(selection_sort(cards, key=lambda c: c[0]))
print(sorted(cards, key=lambda c: c[0]))
[('A', 3), ('B', 2), ('B', 1)]
[('A', 3), ('B', 1), ('B', 2)]
Stability only matters when equal keys are distinguishable, that is, when you sort records by part of their content. Sorting plain integers, equal items are identical and nobody can tell.
Why comparison sorts cannot beat n log n
Bubble, selection, insertion, merge, quick and heap sort are comparison sorts: the only thing they learn about the items is the answer to questions of the form "is a less than b?". That restriction has a provable cost. With n distinct items there are n! possible input orders, and the algorithm must end up doing something different for each of them, since each needs a different rearrangement. Every comparison has two outcomes, so after c comparisons the algorithm can have distinguished at most 2^c different cases. It needs 2^c >= n!, so c >= log2(n!) comparisons in the worst case, and log2(n!) grows like n log2 n. In short: every comparison sort needs Omega(n log n) comparisons in the worst case.
import math
for n in [10, 100, 1000]:
needed = math.ceil(math.log2(math.factorial(n)))
print(f"n = {n:4}: ceil(log2(n!)) = {needed:5}, n * log2(n) = {n * math.log2(n):8.1f}")
n = 10: ceil(log2(n!)) = 22, n * log2(n) = 33.2
n = 100: ceil(log2(n!)) = 525, n * log2(n) = 664.4
n = 1000: ceil(log2(n!)) = 8530, n * log2(n) = 9965.8
Sorting 10 items needs at least 22 comparisons in the worst case, whatever the algorithm. Merge sort and heap sort meet the bound up to a constant factor, which is why they are called asymptotically optimal comparison sorts. Two consequences are worth remembering. First, the bound is about the worst case: insertion sort's O(n) on sorted input does not contradict it. Second, it only covers algorithms that learn by comparing. Counting sort and radix sort read the key values directly, and that is how they reach O(n + k) and O(d(n + k)); the counting sort and radix sort post explains when that is worth it.
What Python's built-in sort does
For almost all real code in Python the answer to "which sort should I use?" is sorted() or list.sort(). The documentation guarantees that both are stable, and the Sorting HOWTO names the algorithm, Timsort, and notes that it takes advantage of any order already present in the data. Timsort is an adaptive merge sort: it finds runs that are already in order and merges them, so it makes O(n log n) comparisons in the worst case and gets close to n comparisons on input that is already sorted. It needs up to O(n) extra memory for merging. Internal details have changed between Python versions, so do not write code that relies on them.
Practical points: sort with key= rather than writing a comparison function; reverse=True keeps the sort stable; and if you need only the few smallest or largest items, heapq.nsmallest and heapq.nlargest avoid sorting everything.
How to choose a sort
- General-purpose sorting in Python: the built-in sort. Writing your own will be slower and is worth doing only to learn.
- A guaranteed O(n log n) with stability: merge sort, if O(n) extra memory is acceptable.
- A guaranteed O(n log n) with O(1) extra memory: heap sort, accepting that it is not stable and is often slower in practice than quicksort.
- Fast average case for in-memory arrays: quicksort with a random or median-of-three pivot, accepting an O(n^2) worst case that random pivots make very unlikely.
- Tiny or nearly sorted inputs: insertion sort, which is why hybrid sorts switch to it for small pieces.
- Integer keys in a small range, or fixed-length keys: counting sort or radix sort.
- Bubble sort and selection sort: for teaching. Selection sort's one real advantage is that it makes at most n - 1 swaps, which matters only when writes are very expensive.
The individual algorithms are explained, with code and traces, in bubble, selection and insertion sort and merge sort and quicksort.
Check yourself
- Which sorts in the table are both stable and O(n log n) in the worst case? (Merge sort only, among the comparison sorts; Python's built-in sort also qualifies.)
- Does insertion sort's O(n) best case break the Omega(n log n) lower bound? (No; the bound is for the worst case over all inputs.)
- You sort orders by date, then stably by customer. What order are the orders in within each customer? (By date.)