Programming Fundamentals · Search and Sorting

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.

Head-to-head · Bubble vs Quicksort

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.

Bar count Both lanes share the same data—hit “Race” to start

🫧 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
How to watch: bubble only ever compares neighbors and inches one cell at a time; each time quicksort picks a pivot, it splits the problem into two smaller ones. With 10 bars they look close; with 60, quicksort’s comparisons are a fraction of bubble’s.
Two ideas · what each playbook is

🫧 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.

Next lesson preview:Sorting has a hidden identity in the AI era. RAG pulls back a pile of candidate passages—whoever ranks first gets into context. That “score + re-rank” step is called Rerank: sorting’s real face in LLM engineering. Next lesson, you’ll play Rerank yourself.

What this lesson wants to share