Sorting is a foundational operation that impacts performance all over the stack: databases, UIs, pipelines, and in-memory processing. The important part is not memorizing algorithms, but understanding stability, memory tradeoffs, and typical runtime behavior. Example: mergesort is stable and predictable, while quicksort is often fast in practice but has worst-case pitfalls.

Diagram

flowchart TD
  A[Need sorting] --> B{Keys are small integers or fixed width}
  B -->|Yes| B1{Key range is comparable to n}
  B1 -->|Yes| B2[Counting Sort]
  B1 -->|No but keys are fixed width| B3[Radix Sort]
  B1 -->|Keys spread uniformly over a range| B4[Bucket Sort]
  B -->|No, comparison sort needed| C{Need stable output}
  C -->|Yes| D{Need O n log n worst case}
  D -->|Yes| E[Merge Sort or Tim Sort]
  D -->|No| F[Insertion Sort only for small or nearly sorted input]
  C -->|No| G{Need in place and fast average case}
  G -->|Yes with worst case guarantee| H[Introsort]
  G -->|Yes| I[Quick Sort]
  G -->|No| J[Selection Sort or Bubble Sort for learning]

Algorithm Selection

Comparison sorts — bounded below by O(n log n)

AlgorithmAverageWorstSpaceStableReach for it when
Bubble SortO(n²)O(n²)O(1)YesTeaching only
Comb Sort~O(n² / 2^p)O(n²)O(1)NoTeaching why bubble sort is slow
Selection SortO(n²)O(n²)O(1)NoWrites are far costlier than reads
Insertion SortO(n²)O(n²)O(1)YesTiny or nearly-sorted input; base case of hybrids
Shell Sort~O(n^1.3)O(n^1.5) with HibbardO(1)NoNo recursion, no scratch memory (embedded)
Heap SortO(n log n)O(n log n)O(1)NoHard worst-case bound with no extra memory
Merge SortO(n log n)O(n log n)O(n)YesStability required; linked lists; external sort
Quick SortO(n log n)O(n²)O(log n)NoCache-friendly in-memory default
Tim SortO(n log n)O(n log n)O(n)YesReal-world partly-ordered data (Python, Java)
IntrosortO(n log n)O(n log n)O(log n)NoQuicksort’s speed without its O(n²) tail (C++, .NET)

Non-comparison sorts — beat the bound by reading key structure

AlgorithmTimeSpaceStablePrecondition
Counting SortO(n + k)O(n + k)YesInteger keys in a small range [0, k)
Radix SortO(d · (n + b))O(n + b)YesFixed-width keys; needs a stable inner sort
Bucket SortO(n + k) avg, O(n²) worstO(n + k)If inner sort isKeys roughly uniform over a known range

Questions

References

13 items under this folder.