TwiddleLab / Code / How a Programmer Thinks
Sorting, One Swap at a Time
What you will learn
- Sorting puts a list in order. Bubble sort compares neighbours and swaps them if they are in the wrong order.
- One pass walks the list once, left to right. The biggest value always ends up at the end.
- Swapping two values needs a spare box, temp, like the swap puzzle.
- Each swap fixes one pair out of order, so a backwards list needs the most work.
How the lesson goes
Eight bars, random heights.
Walk left to right once and swap any neighbours in the wrong order. Where does the tallest bar end up?
Game: sort these bars, swapping neighbours only.
Shortest to tallest, left to right. Match par for three stars.
Now the computer does one pass.
Press Step. Orange frame: swap. Green frame: already in order.
What you just watched has names.
Sorting puts a list in order. There are many ways to do it.
Bubble sort compares neighbours and swaps them if they're in the wrong order. Big values bubble up to the end.
One walk through the list is a pass. Repeat passes until nothing swaps, and the list is sorted.
A swap needs a spare box, temp, just like your swap puzzle. Watch it swap 5 and 2.
Write one pass of bubble sort.
Put the lines in order, then Run. One line is a trap.
Predict the swaps.
Tap every gap where one pass will swap. Careful: a swapped bar keeps moving.
A feed should show the best posts first.
This code sorts post ratings, but the worst post ends up on top. Change one symbol and Run.
Build the list bubble sort hates most.
Tap two bars to swap them. Make every pair out of order, then Check.
How many swaps will bubble sort need for your list?
Race: your hardest list against an almost sorted one.
Same algorithm, same speed. Press Go.
Previous lesson: Lists: Many Boxes in a Row · Next lesson: Finding Things Fast · Part of the course: How a Programmer Thinks
Lessons are interactive and need JavaScript. Turn it on to play them.