Sorting: Bubble Sort vs Quicksort Race
Last lesson said the ticket for binary search is “sort first.” So is sorting itself expensive? Depends on the playbook. Today’s an open race: same shuffled data, bubble sort and quicksort start together—whoever lines the bars short-to-tall first wins. Start small, then try 60 bars—the gap will stick with you.
Rules: two lanes, the same random bars, the same animation pace (each step takes the same time)—a fair race. Watch three things: ① yellow = bars being compared ② purple = the quicksort “pivot” ③ green = already in place. Feel the rhythm with 10 bars, then hit 60 to see the gap.
🫧 Bubble sort
Compare neighbors; the bigger one slowly bubbles right · O(n²) 0 comparisons⚡️ Quicksort
Pick a pivot, split in half, recurse · average O(n log n) 0 comparisons🫧 Bubble: brute-force swap one by one O(n²)
Each pass sweeps left to right; swap neighbors whenever the left one is bigger—after one pass, the biggest has “bubbled” to the far right. Simple, intuitive, hard to get wrong—but n values need n passes, so the bill is n². That red curve from two lessons back? That’s its fate.
⚡️ Quicksort: divide and conquer O(n log n)
Pick a “pivot,” shove shorter bars left and taller ones right—after one pass the pivot is in place, and each pile repeats the same move. “Split in half” ring a bell? It’s binary search’s cousin. That playbook is divide and conquer—it’ll show up again two lessons from now when we cover recursion.
🪪 Honestly: nobody hand-writes sorting
In real engineering, sorting is one line of list.sort()—the language’s built-in beats anything you or I hand-write. So why learn this? For two kinds of feel: one, to see why some code “runs overnight”—usually someone ran an O(n²) playbook on millions of rows; two, to feel how far O(n²) and O(n log n) really are—the race above is the two curves from two lessons back, live. With the ruler and the feel, you’ve got the guts to review AI-written code.
What this lesson wants to share
- Two schools of sorting thought: brute-force swap one by one (bubble) vs divide and conquer (quicksort)
- “Split in half” scores again: quicksort is binary search’s cousin; divide and conquer shows up again with recursion
- At scale, algorithm choice is life or death: 60 bars are already obvious; at a million rows it’s “runs overnight” vs “done in a second”
- You don’t hand-write it—but you must read it: the speed bill behind one .sort() is basic code-review literacy