Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Sorting Algorithms

Every common sort at a glance — time, space, stability, and which one to reach for.

Sorting algorithms are compared on four properties: time (best, average and worst case), extra space, stability (whether equal keys keep their input order) and adaptivity (whether nearly sorted input runs faster). No comparison sort can beat O(n log n) comparisons in the worst case, so the real differences lie in constants, memory behavior and worst-case guarantees.

That is why production libraries use hybrids such as Timsort, introsort and pdqsort that combine several algorithms. Reach for your language’s built-in sort first, and write your own only to exploit structure it cannot see, such as small integer keys.

528193748 runs of one2 51 83 94 74 merges, 4 compares1 2 5 83 4 7 92 merges, 6 compares1 2 3 4 5 7 8 91 merge, 7 compareslog2 8 = 3 levels, ≤ n compares each
Merge sort’s O(n log n) made visible: halving 8 items takes log2 8 = 3 levels, and merging a level touches each item once, so it costs at most n comparisons. This input needed 4 + 6 + 7 = 17.

Comparison sorts

Quicksort
best/avg O(n log n) · worst O(n²) · space O(log n) · not stable · in-place
Merge sort
O(n log n) always · space O(n) · stable
Heap sort
O(n log n) always · space O(1) · not stable · in-place
Insertion sort
best O(n) · avg/worst O(n²) · space O(1) · stable
Selection sort
O(n²) always · space O(1) · not stable
Bubble sort
best O(n) · avg/worst O(n²) · space O(1) · stable
Shell sort
gapped insertion sort: O(n log² n) to O(n^1.5) by gap sequence · in-place · not stable
Cycle sort
O(n²), but the fewest possible writes — for write-limited memory

Hybrid & production sorts

Timsort
merges natural runs, insertion-sorts short ones: O(n) on sorted input, O(n log n) worst · stable
Introsort
quicksort that falls back to heapsort past depth ~2 log n — O(n log n) worst · not stable
pdqsort
pattern-defeating quicksort with fast paths for sorted and repeated data — Go’s default
Dual-pivot quicksort
two pivots, three partitions — Java’s Arrays.sort for primitive arrays
Small-n cutoff
hybrids switch to insertion sort below a few dozen elements, where it is fastest

Non-comparison sorts (beat the n log n bound)

Counting sort
O(n + k) · space O(k) · stable — small integer key range k
Radix sort
O(n·k) for k digits · space O(n + b) for base b · stable — fixed-width integers/strings
Bucket sort
avg O(n + k) · worst O(n²) · space O(n + k) · stable — uniformly spread values
LSD vs MSD radix
LSD sorts least-significant digit first and relies on stability; MSD recurses on prefixes, suits strings

Which sort when

Nearly sorted / tiny n
Insertion sort — near O(n), low overhead
Need stability
Merge sort (or a stable library sort)
Fast average, in-place
Quicksort — but guard against the O(n²) worst case
Guaranteed O(n log n)
Heap (O(1) space) or merge (stable)
Small integer range
Counting / radix — linear, skips comparisons
Uniform real values
Bucket sort — scatter, sort each, concatenate
Bigger than RAM
External merge sort — sort memory-sized runs, then k-way merge them
Only the top k
Heap of size k (O(n log k)), or quickselect then sort the k

Quicksort details

Pivot choice
first or last element is O(n²) on sorted input; pick randomly or median-of-three
Many duplicates
three-way partitioning (Dutch national flag) keeps equal keys out of the recursion
Lomuto vs Hoare
Lomuto is simpler to write; Hoare does about three times fewer swaps on average
Stack depth
recurse into the smaller side, loop on the larger: O(log n) stack guaranteed

Language defaults

Python sorted()
Timsort-based and stable; prefer key=; list.sort() sorts in place and returns None
Java Arrays.sort
primitives: dual-pivot quicksort, not stable · objects: Timsort, stable
C++ std::sort
introsort, not stable; std::stable_sort keeps order, std::partial_sort for top-k
JS Array.sort
stable since ES2019, but compares as strings unless you pass a comparator
Go slices.Sort
pdqsort, not stable; use slices.SortStableFunc when equal items must keep order
Rust sort · sort_unstable
sort is a stable merge-based sort; sort_unstable is a faster quicksort variant

Related problems

Quickselect
k-th smallest in O(n) average; median-of-medians makes the worst case O(n) too
Count inversions
merge sort counts out-of-order pairs while merging, in O(n log n)
Merge k sorted lists
min-heap of the k current heads: O(n log k) for n items in total
Each item ≤ k away
a heap of size k+1 sorts it in O(n log k); insertion sort takes O(nk)

Gotchas

[10, 9, 1].sort()
JavaScript compares as strings → [1, 10, 9]; pass (a, b) => a - b
Multi-key sort
with a stable sort, sort by the secondary key first, then by the primary
Broken comparator
one that is not a consistent ordering can throw (Java) or corrupt memory (C++)
NaN in floats
NaN compares false with everything, so a list containing it can come back unsorted

Key facts

Comparison lower bound
Any comparison sort needs Ω(n log n) in the worst case
Stable
Equal keys keep their original relative order
In-place
Uses O(1) (or O(log n)) extra space beyond the input
Non-comparison
Uses key structure (digits, counts) to beat n log n — needs bounded keys

Worked example: LSD radix sort, one digit per pass

Sort [170, 45, 75, 90, 802, 24, 2, 66] one decimal digit at a time, ones first. Each pass is a stable counting sort on that digit: drop every number into one of 10 buckets, then read the buckets back in order.

pass       result
ones       170  90 802   2  24  45  75  66
tens       802   2  24  45  66 170  75  90
hundreds     2  24  45  66  75  90 170 802
  1. Ones. 170 and 90 end in 0, so they lead. 802 and 2 both end in 2 and keep their input order.
  2. Tens. 802 and 2 share tens digit 0 and keep their order from the ones pass; 170 and 75 share 7. After this pass the list is sorted by its last two digits.
  3. Hundreds. Six numbers share hundreds digit 0. Stability keeps them in the order the tens pass left them, 2, 24, 45, 66, 75, 90, which is already correct. An unstable pass could scramble them.

Cost: 3 passes × (8 items + 10 buckets), and no comparisons at all. Any comparison sort needs ⌈log2 8!⌉ = 16 comparisons in the worst case for these 8 items. At this size the bucket bookkeeping wins nothing; radix pays off when n is large and keys are short, such as 32-bit integers in 4 passes of base 256.

Recipes

Sort records by two keys with a stable sort (Python)

employees.sort(key=lambda e: e.name)   # secondary key first
employees.sort(key=lambda e: e.dept)   # then the primary key

# the same result in one pass
employees.sort(key=lambda e: (e.dept, e.name))

Because the sort is stable, the second pass keeps names in order within each department; a tuple key does both at once, and a negated number sorts a numeric field descending.

One quicksort partition, traced (Lomuto)

array [5, 3, 8, 1, 9, 2], pivot = 2 (last element), i = -1
j=0: 5 > 2, skip
j=1: 3 > 2, skip
j=2: 8 > 2, skip
j=3: 1 <= 2, i = 0, swap a[0] and a[3]  → [1, 3, 8, 5, 9, 2]
j=4: 9 > 2, skip
swap a[i+1] with the pivot              → [1, 2, 8, 5, 9, 3]
the pivot is final at index 1; recurse on [1] and [8, 5, 9, 3]

Everything left of the pivot is smaller and everything right is larger. A pivot this close to the minimum leaves one side nearly empty, which is how bad pivots make quicksort slow.

External merge sort of a 100 GB file (worked example)

File and memory:  100 GB of data, 8 GB of RAM
Pass 1:           read 8 GB at a time, sort it in memory, write 13 sorted runs
Pass 2:           k-way merge the 13 runs with a min-heap of their 13 heads
Disk traffic:     each byte read twice and written twice ≈ 400 GB
Time at 1 GB/s:   ≈ 400 seconds of sequential I/O

Every read and write is sequential, which keeps the sort disk-friendly; with too many runs to merge at once, merge them in rounds.

Fix a JavaScript numeric sort

[10, 9, 1, 100].sort()                  // [1, 10, 100, 9]: compared as strings
[10, 9, 1, 100].sort((a, b) => a - b)   // [1, 9, 10, 100]
users.sort((a, b) => a.name.localeCompare(b.name))   // text, locale-aware

Without a comparator, elements are converted to strings and compared by UTF-16 code units; a comparator returns a negative, zero or positive number.

When to use it, and when not

Call the built-in sort. It is stable in Python, JavaScript, Rust’s sort and Java’s object sort, fast on partly ordered data, and tested far beyond anything hand-written. Write something else only when the job is not really “sort everything once”:

  • You need only part of the order. Minimum or maximum is one O(n) pass. The median or k-th item is quickselect. The top k is a size-k heap, as in heapq.nlargest.
  • Items keep arriving. Re-sorting after each insert costs O(n log n) every time. Keep a heap if you only ever take the smallest, or a balanced tree or sorted container if you also iterate in order.
  • Keys are small integers. Ages, star ratings or bytes: counting sort is one pass plus a histogram.
  • The data is in a database. ORDER BY on an indexed column returns rows already in order; fetching everything and sorting in the application wastes memory and bandwidth.
  • You only need lookups. Membership tests and deduplication want a hash set, O(1) on average per item, not a sort.

Trade-offs and limits

Big-O ties the main comparison sorts at O(n log n), so the choice comes down to what else each one costs.

CostWho pays itWhat it means
Extra memoryMerge sortA second buffer of n slots: 100 million 8-byte values need another 800 MB
Bad worst caseUnguarded quicksortO(n²) on adversarial or already sorted input; introsort caps it
InstabilityHeap sort, quicksort, introsortEqual keys come out reordered; C++ std::stable_sort drops to O(n log² n) when it cannot allocate a buffer
Comparison costExpensive keysPython’s key= runs once per item; a comparator via cmp_to_key runs on every comparison, about n log2 n times
Key limitsCounting and radix sortNeed bounded or fixed-width keys; counting sort over values up to 10⁹ needs a billion counters

Common mistakes

  • Sorting inside a loop. Appending and re-sorting on every new item is O(n² log n) overall. Use heapq, or bisect.insort when the list stays small.
  • Sorting a dict and getting keys. sorted(d) returns the keys only. To order by value, sort the items: sorted(d.items(), key=lambda kv: kv[1]).
  • A boolean comparator in JavaScript. (a, b) => a > b returns true or false, never a negative number, so the engine is never told “a comes first”. In Node 22, [3, 1, 2].sort((a, b) => a > b) returns [3, 1, 2] unchanged.
  • Forgetting case. Code-point order puts every capital first: sorted(['banana', 'Zebra', 'apple']) gives ['Zebra', 'apple', 'banana']. Use key=str.casefold in Python or localeCompare in JavaScript.
  • Reversing instead of reverse=True. sorted(xs, key=k, reverse=True) keeps equal items in input order; sorted(xs, key=k)[::-1] flips them, which silently breaks a multi-pass sort.

Check yourself

How many comparisons does insertion sort make on 1,000 items already sorted, and on 1,000 in reverse order?

999 when sorted (one per item after the first) and 499,500 when reversed: n(n − 1)/2.

What does sorted([('b', 2), ('a', 2), ('c', 1)], key=lambda t: t[1]) return?

[('c', 1), ('b', 2), ('a', 2)]. The sort is stable, so b stays ahead of a.

What does [3, 20, 100].sort() return in JavaScript?

[100, 20, 3]. Without a comparator the numbers compare as strings, and “1” < “2” < “3”.

What is the fewest comparisons that can sort any 4 items in the worst case?

5. There are 4! = 24 orders, each comparison at most halves them, and ⌈log2 24⌉ = 5; a 5-comparison method exists.

Questions about Sorting Algorithms Cheat Sheet

What is the fastest sorting algorithm?

There is no single fastest one; it depends on the data. For general comparison sorting, well-engineered quicksort variants such as introsort and pdqsort are usually fastest in practice, thanks to in-place partitioning and good cache behavior, while Timsort excels on data that is already partly ordered. When keys are small integers or fixed-width values, counting sort and radix sort beat every comparison sort by avoiding comparisons altogether. In real code the built-in sort is almost always the right choice, because it already combines these algorithms carefully.

What is a stable sort and why does it matter?

A sort is stable when elements that compare equal keep the relative order they had in the input. It matters whenever records carry more than the sort key: sorting orders by date with a stable sort keeps orders from the same date in their previous order, for example by customer if they were sorted that way first. That property lets you build multi-key sorts from several single-key passes. Merge sort, insertion sort, Timsort and counting sort are stable; quicksort, heapsort and selection sort normally are not.

Why is quicksort faster than merge sort in practice?

Big-O hides constant factors and memory behavior. Quicksort partitions in place, scanning memory sequentially in tight loops, so it uses CPU caches well and needs no extra array, while merge sort copies elements into an auxiliary buffer of size n at every level. Quicksort’s weakness is its O(n²) worst case with poor pivots, which production versions avoid through random or median-of-three pivots and a fallback to heapsort. Merge sort remains the better choice when you need stability, a guaranteed O(n log n), or to sort linked lists or external data.