8 Foundational Algorithms · Pure Comparison

The Quiet Anatomy of Sorting

No racing bars or noisy animations—just a calm, clear comparison of how the classics trade speed, memory, stability, and real-world elegance.

Ω(n log n) Barrier

No comparison-based sort can beat log-linear time in the general worst or average case. Only key-based sorts like Radix sidestep it.

Cache Over Theory

Hardware loves sequential memory. Quick Sort and Insertion Sort often outperform rivals with tighter theoretical bounds.

Hybrids Win Production

Modern standard libraries blend strategies—like Timsort and Introsort—to harvest speed on both random and nearly-ordered data.

Filter algorithms by characteristic
Filters both matrix & cards below
01 · Side by Side

Complexity Matrix

Time complexity measures growth as input size n rises; space complexity tracks extra memory beyond the input array.

Algorithm Best Average Worst Extra Space Stable In-Place Sweet Spot
Quick Sort Divide & Conquer
O(n log n) O(n log n) O(n²) O(log n) call stack No Yes Fast general-purpose in-memory arrays
Merge Sort Divide & Conquer
O(n log n) O(n log n) O(n log n) O(n) Yes No Guaranteed speed, linked lists, external disk sorts
Timsort Adaptive Hybrid
O(n) O(n log n) O(n log n) O(n) Yes No Real-world partially ordered data & objects
Heap Sort Binary Heap Selection
O(n log n) O(n log n) O(n log n) O(1) No Yes Strict memory limits & worst-case guarantees
Insertion Sort Incremental · Adaptive
O(n) O(n²) O(n²) O(1) Yes Yes Tiny partitions (n ≤ 32) & nearly-sorted streams
Selection Sort Minimal-Write Selection
O(n²) O(n²) O(n²) O(1) No Yes Rare cases where writes cost far more than reads
Bubble Sort Adjacent Exchange
O(n) early exit O(n²) O(n²) O(1) Yes Yes Teaching invariants & simple sortedness checks
Radix Sort (LSD) Non-Comparative
O(d(n+k)) O(d(n+k)) O(d(n+k)) O(n + k) d digits, base k Yes No Huge arrays of fixed-width integers or keys
Linear / Constant Fast or lean Log-Linear Optimal comparison scaling Key-Based Non-comparative Linear Space Auxiliary buffer Quadratic Heavy at scale
Click any algorithm name to jump to its notes
02 · Field Notes

Algorithm Profiles

Every algorithm carries a distinct personality—how it moves through memory, where it shines, and where it stumbles.

Quick Sort

Divide & Conquer · Partitioning
In-Place Unstable

Picks a pivot, sweeps smaller values to its left and larger values to its right, then recurses on each side. Tight sequential scans make it extraordinarily friendly to CPU caches.

BestO(n log n)
AverageO(n log n)
WorstO(n²)
MemoryO(log n)

Strengths

  • Low constant overhead and strong cache locality
  • No extra heap array needed beyond call stack
  • 3-way partitioning handles heavy duplicates swiftly

Trade-offs

  • Poor pivot selection triggers O(n²) collapse
  • Unstable—equal elements may change order
  • Needs median-of-three or randomization in practice
Core idea & pseudocode
function quickSort(A, lo, hi):
  if lo >= hi: return
  p = partition(A, lo, hi)  // pivot lands in final spot
  quickSort(A, lo, p - 1)
  quickSort(A, p + 1, hi)
Seen in: Java Arrays.sort for primitives (Dual-Pivot Quicksort), C++ std::sort (as Introsort's primary engine).

Merge Sort

Divide & Conquer · Linear Merging
Stable O(n) Buffer

Divides the input cleanly in half until sublists hold one element, then zips sorted pairs together in linear passes. Calm, steady, and immune to adversarial input orderings.

BestO(n log n)
AverageO(n log n)
WorstO(n log n)
MemoryO(n)

Strengths

  • Strict O(n log n) across all possible inputs
  • Naturally stable for chained multi-key sorting
  • Ideal for linked lists and huge disk-based datasets

Trade-offs

  • Allocates O(n) auxiliary space on arrays
  • Extra data copying slows it slightly on small RAM arrays
  • Vanilla version ignores pre-existing sorted runs
Core idea & pseudocode
function mergeSort(A):
  if len(A) <= 1: return A
  mid   = len(A) // 2
  left  = mergeSort(A[:mid])
  right = mergeSort(A[mid:])
  return merge(left, right) // weave smallest heads
Seen in: External database merge sorts (PostgreSQL), C++ std::stable_sort, linked list sorting.

Timsort

Adaptive Hybrid · Merge + Insertion
Stable Adaptive

Crafted for real-world data, which rarely arrives uniformly scrambled. It discovers natural ascending or descending runs, pads short runs with Insertion Sort, and merges them smartly with galloping search.

BestO(n)
AverageO(n log n)
WorstO(n log n)
MemoryO(n)

Strengths

  • Flies in O(n) on already or nearly sorted collections
  • Combines worst-case safety with full stability
  • Minimizes expensive comparison callbacks on objects

Trade-offs

  • Intricate stack-invariant logic to implement from scratch
  • Uses up to O(n) temporary merge memory
  • Slight setup overhead on tiny purely random arrays
Core idea & pseudocode
function timSort(A):
  while items remain in A:
    run = detectNaturalRun(A)  // reverse if descending
    if len(run) < minRun:
      binaryInsertionSort(run, to = minRun)
    push run to stack; mergeBalancedRuns(stack)
  mergeRemaining(stack)
Seen in: Python sorted() & list.sort(), Java object sorting, V8 JavaScript engine, Android.

Heap Sort

Binary Heap · Guaranteed Bounds
In-Place O(1) Space

Sculpts the array itself into a max-heap, then repeatedly swaps the peak element to the tail and sifts the shortened heap back into order. Pure worst-case discipline with zero extra allocation.

BestO(n log n)
AverageO(n log n)
WorstO(n log n)
MemoryO(1)

Strengths

  • Rock-solid O(n log n) worst case without exceptions
  • Strictly O(1) extra space (iterative, zero stack growth)
  • Perfect fallback guard inside Introsort & kernels

Trade-offs

  • Jumps across indices (i → 2i+1), hurting CPU cache hits
  • Unstable due to long-range root-to-leaf swaps
  • Usually slower in wall-clock time than Quick Sort
Core idea & pseudocode
function heapSort(A):
  buildMaxHeap(A)            // O(n) Floyd heapify
  for end = len(A) - 1 downto 1:
    swap(A[0], A[end])       // place current max at tail
    siftDown(A, 0, end - 1)
Seen in: Linux kernel lib/sort.c, C++ Introsort recursion-depth fallback, embedded real-time systems.

Insertion Sort

Incremental · Card-Hand Method
Stable In-Place

Grows a sorted prefix from left to right, sliding each incoming element gently back into its rightful slot—just like organizing playing cards in your hand.

BestO(n)
AverageO(n²)
WorstO(n²)
MemoryO(1)

Strengths

  • Fastest practical sort on small arrays (n ≤ 16–32)
  • O(n) on nearly-sorted data; works online as data arrives
  • Tiny code, stable, and zero auxiliary allocation

Trade-offs

  • O(n²) element shifts choke on large unsorted arrays
  • Reverse-ordered input hits maximum shifting work
Core idea & pseudocode
function insertionSort(A):
  for i = 1 to len(A) - 1:
    key = A[i]; j = i - 1
    while j >= 0 and A[j] > key:
      A[j + 1] = A[j]; j -= 1
    A[j + 1] = key
Seen in: The final base-case engine inside Timsort, Introsort, and tuned Quicksort implementations.

Selection Sort

Incremental · Minimal Swaps
In-Place ≤ n−1 Swaps

Scans the entire unsorted suffix to find its exact minimum, then swaps it once into the front boundary. Blind to existing order, yet uniquely gentle on memory writes.

BestO(n²)
AverageO(n²)
WorstO(n²)
MemoryO(1)

Strengths

  • Performs at most n − 1 writes (ideal for write-limited media)
  • Minimal mental model and O(1) extra space
  • Completely predictable comparison count

Trade-offs

  • Always O(n²) comparisons—even if already sorted
  • Unstable because distant swaps leapfrog equal keys
  • Generally slower than Insertion Sort in practice
Core idea & pseudocode
function selectionSort(A):
  for i = 0 to len(A) - 2:
    minIdx = i
    for j = i + 1 to len(A) - 1:
      if A[j] < A[minIdx]: minIdx = j
    swap(A[i], A[minIdx])   // single swap per pass
Seen in: Classroom benchmarks and niche hardware (EEPROM/Flash) where write cycles are heavily rationed.

Bubble Sort

Exchange · Adjacent Swaps
Stable Educational

Walks the array comparing adjacent neighbors and flipping inverted pairs, letting the largest unsorted value drift to the right boundary on each pass.

BestO(n)
AverageO(n²)
WorstO(n²)
MemoryO(1)

Strengths

  • Crystal-clear introduction to loops and invariants
  • Early-exit flag confirms sorted input in one O(n) sweep
  • Preserves equal-key order (stable) in O(1) space

Trade-offs

  • Heavy swap churn makes it the slowest quadratic classic
  • Small values near the end ("turtles") crawl back one step per pass
Core idea & pseudocode
function bubbleSort(A):
  for end = len(A) - 1 downto 1:
    swapped = false
    for i = 0 to end - 1:
      if A[i] > A[i + 1]:
        swap(A[i], A[i + 1]); swapped = true
    if not swapped: break   // already ordered
Seen in: Computer science pedagogy and historical contrast against Insertion and Merge Sort.

Radix Sort (LSD)

Non-Comparative · Digit Distribution
Stable Breaks Ω(n log n)

Never asks "is A less than B?" Instead, it distributes keys into buckets one digit or byte at a time—from least to most significant—relying on a stable Counting Sort at each pass.

BestO(d(n+k))
AverageO(d(n+k))
WorstO(d(n+k))
MemoryO(n + k)

Strengths

  • Surpasses O(n log n) when digit width d is bounded
  • Linear scaling on millions of 32/64-bit integers
  • Stable and exceptionally parallelizable on GPUs

Trade-offs

  • Limited to decomposable keys (integers, fixed strings)
  • Cannot accept arbitrary custom comparison functions
  • Needs O(n + k) extra space and has larger constant factors
Core idea & pseudocode
function radixSortLSD(A, base = 256):
  for digit = 0 to maxDigits - 1:
    // stable pass preserves lower-digit ordering
    A = countingSortByDigit(A, digit, base)
  return A
Seen in: High-throughput GPU sorting (CUDA CUB/Thrust), suffix arrays, massive integer/IP datasets.
03 · Practical Instinct

When to Reach for What

There is no single "best" sorting algorithm—only the best match for your data shape, hardware, and guarantees.

Everyday production & mixed real-world data

Timsort Default Choice

Exploits pre-existing order in timestamps, logs, and user lists while remaining stable and safe in the worst case.

Raw speed on in-memory primitive arrays

Quick Sort / Introsort Cache King

Sequential scans saturate CPU caches. Pair Quicksort with a Heap Sort depth guard (Introsort) to erase O(n²) risk.

Tiny arrays (n ≤ 32) or streaming insertions

Insertion Sort Zero Friction

Beats fancier O(n log n) routines on tiny slices because its inner loop has almost no branching or setup cost.

Tight RAM budgets & hard real-time deadlines

Heap Sort O(1) Space

Zero heap allocation, zero recursion stack risk, and a strict O(n log n) ceiling—why the Linux kernel trusts it.

Linked lists or files larger than RAM

Merge Sort Sequential I/O

Needs no random index jumps—merges pointer chains in-place on linked lists and streams cleanly across disk chunks.

Millions of fixed-width integers or hashes

Radix Sort Past Ω(n log n)

When keys decompose cleanly into bytes, 4 or 8 linear passes can outrun comparison sorts by a wide margin.

04 · Vocabulary

Four Properties That Matter

Understanding these four axes explains nearly every trade-off in the comparison matrix above.

Stability

A stable sort keeps equal keys in their original relative order. Sort contacts by name, then stably by city, and every city stays alphabetical.

In-Place Memory

An in-place algorithm rearranges elements within the original buffer, needing only O(1) or O(log n) auxiliary workspace instead of cloning the full array.

Adaptivity

An adaptive sort accelerates when data is already partly sorted—dropping from O(n log n) or O(n²) down toward linear O(n) work.

Cache Locality

Modern CPUs fetch memory in contiguous cache lines. Algorithms touching nearby indices sequentially (Quick, Insertion) often beat algorithms jumping randomly (Heap).