In many real-life situations, people need to arrange a collection of items according to a particular order. For example, organizing products by price, arranging students by height, ordering files by name, or arranging scores from highest to lowest. When the items are not in the desired order, they need to be rearranged through a series of changes.
Let's play a game where you'll rearrange a line of items into the desired order. Compare the items carefully, change their positions when needed, and keep moving through the line until everything is arranged correctly.
Let's see exactly what that looks like ๐
Seven students must line up shortest to tallest before the photographer loses patience. The playground is packed, so a student may only swap places with the neighbour right beside them.
Notice how the tallest student ended up at the end after each round of comparisons? By repeatedly checking neighbouring students and swapping only when needed, the line gradually became completely sorted without moving everyone at once.
Before the photographer moves on, a few things worth thinking about. No need to write anything down.
Everything you just did in the game has a name. Here's the algorithm behind it.
It's called Bubble Sort because, pass after pass, the largest remaining value keeps "bubbling up" toward the end of the line, one comparison and one possible swap at a time, just like a bubble rising to the surface of water.
This is the exact same idea as the game, shrunk down to five numbers. Use the Forward button to step through it or hit play and watch the pseudocode light up in sync with what's happening below.
Pass 1
Only two students standing right next to each other are ever compared, never elements that are far apart in the line.
If the left one is taller than the right one, they swap places. If they're already in order, nothing happens and we move on.
By the time a full pass finishes, the largest remaining value has "bubbled" all the way to its correct spot at the end.
If an entire pass goes by with zero swaps, every element must already be in order, so the algorithm can stop early.
A proof sheet of harder questions to think through. Open-ended, no single right answer.