Sorting Things Out
How do computers put things in order? Learn to sort numbers by comparing neighbors and swapping them, just like the famous bubble sort.
Welcome back!
Step 1 of 12Learn
Why sort?
Sorting means putting things in order: smallest to biggest, A to Z, or shortest to tallest.
Sorted things are easier to use. A sorted list of names lets you find a friend quickly. A sorted high-score table shows the winner at the top. And remember, binary search needs a sorted list.
You sort things all the time: lining up by height, putting books on a shelf, organizing cards in your hand.
Step 2 of 12Practice · Put in order
Sort these numbers from smallest to biggest.
Drag the items, or use the arrow buttons, to put them in order.
- 3
- 8
- 21
- 15
- 40
Step 3 of 12Learn
Compare and swap
A computer cannot look at a whole list at once like you do. It can only compare two things at a time.
One famous method is bubble sort:
- Look at the first two numbers.
- If the left one is bigger, swap them.
- Move one place right and do it again.
- When you reach the end, start over.
- Stop when you can go all the way through with no swaps.
The biggest numbers "bubble up" to the end, like bubbles rising in a drink.
Step 4 of 12Practice · Chart
A list to sort: 4, 2, 3, 1
After one pass of bubble sort, which bar has bubbled to the end? Tap it.
Tap the bar that answers the question, then press Check.
Step 5 of 12Tap to reveal
Bubble sort on 4, 2, 3, 1
Pass 1
Compare 4 and 2, swap: 2, 4, 3, 1. Compare 4 and 3, swap: 2, 3, 4, 1. Compare 4 and 1, swap: 2, 3, 1, 4. The 4 bubbled to the end.
Pass 2
Compare 2 and 3, no swap. Compare 3 and 1, swap: 2, 1, 3, 4. Now 3 is in place too.
Pass 3
Compare 2 and 1, swap: 1, 2, 3, 4. Sorted!
Pass 4
Go through again: no swaps at all, so the algorithm stops.
Step 6 of 12Practice · Choose one
In bubble sort, you compare 9 and 5, with 9 on the left. What do you do?
Step 7 of 12Practice · Choose one
The list is 1, 2, 3, 4. Bubble sort goes through it once. How many swaps does it make?
Step 8 of 12Note
Step 9 of 12Practice · True or false
A computer sorts a list by comparing two items at a time.
Step 10 of 12Diagram
One bubble sort move
Tap a shape with to see more.
- Look at two neighbors
- Is the left one bigger?
- Yes: swap them
No? Leave them alone.
- Move one step right
At the end, start again until a pass has no swaps.
Step 11 of 12Practice · Code challenge
biggest(list) should return the biggest number in a list. It walks through the list and keeps the best number so far, but there is a bug: it keeps the smallest instead. Fix the comparison.
biggest([4, 9, 2])biggest([7, 3, 5, 1])biggest([1, 2, 3, 10])
Step 12 of 12Practice · Sort into groups
Is each list already sorted from smallest to biggest?
Tap an item, then tap its group (or drag it there).
Lesson complete!