Course outline · 0% complete

0/30 lessons0%

Course overview →

How sorting works: bubble and selection

lesson 3-1 · ~12 min · 6/30

Quiz

Warm-up from lesson 2-2: binary search finds items in O(log n), but it has one hard requirement. What is it?

Bubble sort: the teaching sort

Bubble sort is the simplest sorting algorithm to understand, and understanding it teaches you how to reason about sorts.

The idea: sweep left to right, comparing each adjacent pair. If the pair is out of order, swap it. One full sweep is a pass. After the first pass, the largest value has "bubbled" all the way to the end, so the next pass can stop one cell earlier.

Repeat until a pass makes zero swaps, which means the list is sorted.

Nobody ships bubble sort (it is O(n²)), but interviewers still ask you to explain it, and its pass-by-pass trace is the clearest picture of what sorting actually does.

one pass: compare each adjacent pair, swap if out of order53812after the pass, the largest value has bubbled to the end
The gold comparison window sweeps across adjacent pairs. When the pass ends, the last cell is locked in place and the next pass stops one cell earlier.

Code exercise · python

Run this. Each printed line is the list after one full pass. Watch 8 reach the end after pass 1, then 5, then the early exit when a pass swaps nothing.

Selection sort: the other O(n²) classic

Selection sort reaches the same sorted result with a different move. Instead of swapping neighbors, it selects the right value for each position directly: find the smallest value in the whole list and swap it into position 0. Find the smallest of what remains and swap it into position 1. Repeat until every position is filled.

Two facts worth knowing before you write it below:

  • It always does about n²/2 comparisons — even on an already-sorted list — because "find the smallest of the rest" must scan the rest every single time. Bubble sort's zero-swap early exit beats it on nearly-sorted data.
  • It never does more than n swaps (at most one per position). That mattered historically when a swap was expensive — moving a large record on a slow disk — while bubble sort can make O(n²) swaps.

Interviewers pair these two sorts because comparing them forces the real question: what does each pass actually guarantee? A bubble pass guarantees the largest value reaches the end; a selection pass guarantees the smallest values are locked in at the front.

Code exercise · python

Your turn: selection sort, the other O(n²) classic. For each position i from left to right, find the index of the smallest value in nums[i:], then swap it into position i.

Quiz

You run selection sort on an already-sorted list. Roughly how many comparisons does it make?

Quiz

Bubble sort and selection sort are both O(n²). Why does that make them impractical for big data?