← All animations

📊 Sorting Algorithms Visualized

Sorting is rearranging a list into order — and there are many ways to do it. Some plod through every pair of items (slow but simple); others cleverly divide the work in half again and again (fast, but trickier). Watch each algorithm shuffle the same bars into a clean staircase, count the work it does, and then race them head-to-head to feel the difference between O(n²) and O(n log n).

1. The visualiser — watch one algorithm work

Pick an algorithm and press Play. Bars being compared glow gold; bars being swapped or written flash orange; bars that are finished and in place turn green. The counters track every comparison and swap/write the algorithm performs.

0 comparisons · 0 swaps
unsorted comparing swapping / writing sorted

2. The race — same data, every algorithm at once

Now the identical shuffled array is handed to several algorithms simultaneously. Each lane advances at the same rate (one operation per tick), so you literally watch the O(n²) sorts crawl while the O(n log n) sorts snap into place. The first to finish wins — and it's rarely close.

Press Start race

3. Why the difference? Comparisons, swaps & big-O

Every sort does two basic kinds of work. A comparison asks "is A bigger than B?"; a swap (or write) actually moves elements around. The cost of an algorithm is how fast that work grows as the list gets longer — its big-O.

The slow trio — bubble, insertion, selection — each compare roughly every element against every other, so work grows with the square of the size: double the list, do four times the work. Doubling a 1,000-item list to 2,000 jumps from ~1,000,000 to ~4,000,000 operations.
Merge and quick instead split the list in half repeatedly. There are only ~log₂(n) levels of splitting, and each level touches every element once — so work grows as n log n. Double a 1,000-item list to 2,000 and the work barely doubles, not quadruples. For a million items that's the difference between ~20 million operations and ~1 trillion.
AlgorithmBestAverageWorstIdea
BubbleO(n)O(n²)O(n²)Repeatedly swap adjacent out-of-order pairs; largest "bubbles" to the end each pass.
InsertionO(n)O(n²)O(n²)Grow a sorted prefix, sliding each new item back to its slot.
SelectionO(n²)O(n²)O(n²)Find the smallest remaining item and swap it to the front; few swaps, many compares.
MergeO(n log n)O(n log n)O(n log n)Split in half, sort each half, then merge the two sorted halves.
QuickO(n log n)O(n log n)O(n²)Pick a pivot, partition smaller/larger around it, recurse on each side.

Note: selection makes the fewest swaps (at most n−1) but always pays full comparison cost; bubble on an already-sorted list can finish in one O(n) pass. Quick is usually fastest in practice despite its O(n²) worst case, which good pivot choice avoids.