Sorting Algorithms

Sorting is one of the most studied problems in computer science. Choosing the right algorithm depends on your data size, memory budget, stability requirements, and value distribution. Click any card below to dive into its full interactive walkthrough.

Algorithms covered
11
Fastest average
O(n log n)
Non-comparison min
O(n + k)
Used in Python / Java
Tim Sort

Basic Sorts

O(n²)

Simple, educational — great starting point

Efficient Sorts

O(n log n)

Used in real applications — optimal complexity

Non-Comparison Sorts

O(n + k)

Beat the O(n log n) barrier with special tricks

Special Mentions

Hybrid

Hybrid or niche — worth knowing

📐

Why can't comparison sorts beat O(n log n)?

Any algorithm that sorts by comparing pairs must make at least log₂(n!) comparisons in the worst case. By Stirling's approximation, log₂(n!) ≈ n log n. This is a proven theoretical lower bound — you cannot do better with comparisons alone. Non-comparison sorts (Counting, Radix, Bucket) sidestep this by using extra information about the data.

Full Complexity Comparison

AlgorithmBestAverageWorstSpaceStableFast?
🫧Bubble SortO(n)O(n²)O(n²)O(1)
🎯Selection SortO(n²)O(n²)O(n²)O(1)
🃏Insertion SortO(n)O(n²)O(n²)O(1)
🔀Merge SortO(n log n)O(n log n)O(n log n)O(n)🔥
Quick SortO(n log n)O(n log n)O(n²)O(log n)🔥
🌲Heap SortO(n log n)O(n log n)O(n log n)O(1)🔥
🧮Counting SortO(n+k)O(n+k)O(n+k)O(k)🔥
🔢Radix SortO(nk)O(nk)O(nk)O(n+k)🔥
🐍Tim SortO(n)O(n log n)O(n log n)O(n)🔥
O(n²) — quadratic, slow for large nO(n log n) — optimal for comparison sortsO(n+k) — linear (non-comparison)k = value range, n = element count

How to Pick the Right Sort

No single sort wins everything. Here's a practical decision guide:

📌 Small dataset (< 20 items)

🃏Insertion Sort

Low overhead, excellent on tiny or nearly-sorted data

📌 Need guaranteed O(n log n)

🔀Merge Sort

No worst-case degeneracy, always splits evenly

📌 In-place, fast in practice

Quick Sort

Best cache performance, tiny constant factors

📌 Integers in small range

🧮Counting Sort

Beats comparison lower bound — O(n+k) is linear

📌 Need stability (e.g. sort by name then age)

🐍Tim Sort / Merge Sort

Equal elements preserve original relative order

📌 Streaming / online data

🃏Insertion Sort

Can insert new element into sorted prefix immediately

📌 Memory constrained

🌲Heap Sort

O(1) extra space + guaranteed O(n log n)

📌 Uniformly distributed floats

🪣Bucket Sort

Average O(n) when distribution is uniform

What is Stability?

A sort is stable if equal elements maintain their original relative order after sorting.

Example: You have a list of students sorted by name. You then sort by grade. A stable sort will keep students with the same grade in alphabetical order (their previous order). An unstable sort may scramble them.

Stable: Bubble, Insertion, Merge, Counting, Radix, Tim Sort
Unstable: Selection, Quick Sort, Heap Sort, Shell Sort