Tutorpip← About this lessonOpen the sheet →Download PDF
Ages 8+ · Coding · Patterns and algorithms
Sorting by hand
The height of each card0123454422551133
Jonah's five cards, before sorting.
The big ideaSort by comparing two neighbours and swapping them if they are out of order.

How it works

To sort, look at two cards that sit side by side. If the bigger card is on the left, swap them. If they are already in order, leave them alone.

Go along the whole row, pair by pair. That trip is one pass.

Each pass sends the biggest card that is left over to its place.

Make pass after pass, and stop when a whole pass needs no swaps.

The pair• 4 and 2: swap• 4 and 5: leave• 5 and 1: swap• 5 and 3: swapThe row after• 2, 4, 5, 1, 3• 2, 4, 5, 1, 3• 2, 4, 1, 5, 3• 2, 4, 1, 3, 5
Pass one on 4, 2, 5, 1, 3.

Example 1: One pass

  1. The row is 4, 2, 5, 1, 3. Bo swaps 4 and 2, and the row is 2, 4, 5, 1, 3.
  2. 4 and 5 are in order, so he leaves them.
  3. He swaps 5 and 1, then 5 and 3.
  4. The row is 2, 4, 1, 3, 5, and the biggest card, 5, has floated to the end.

Example 2: Pass two

  1. The row is 2, 4, 1, 3, 5. 2 and 4 stay.
  2. 4 and 1 swap, and 4 and 3 swap. 4 and 5 stay.
  3. The row is 2, 1, 3, 4, 5.

Example 3: Pass three, and the check

  1. The row is 2, 1, 3, 4, 5. 2 and 1 swap, and the other pairs are in order.
  2. The row is 1, 2, 3, 4, 5.
  3. Pass four has no swaps at all, so the row is sorted. It took four passes.

Example 4: A small row

  1. The row is 3, 1, 2. Pass one swaps 3 and 1 to give 1, 3, 2, then swaps 3 and 2 to give 1, 2, 3.
  2. Pass two has no swaps, so the row is sorted.

Words to know

pass
One trip along the whole row, pair by pair.
neighbors
Two cards that sit side by side.
swap
Put two cards in each other's places.
sorted
In order, from smallest to biggest.

Watch out

Try it

  1. In the row 2, 5, 3, do 5 and 3 swap?
  2. In the row 2, 5, 9, does Bo swap 5 and 9?
  3. After a pass, where does the biggest card end up?
  4. When is a row sorted?
  5. The row is 2, 1, 3. How many swaps in pass one?
Answers: 1. Yes · 2. No · 3. At the end of the row · 4. When a whole pass needs no swaps · 5. 1
Try at homePick five things of different sizes. Mix them up in a row. Now sort them the robot way: look only at two neighbours at a time, swap them if the bigger one is on the left, and keep going along the row until a whole pass needs no swaps. Count the passes!
For grown-upsPlay the Mission: pick five things of different sizes, mix them up in a row, and have your child sort them the robot way, looking only at two neighbors at a time, swapping when the bigger one is on the left. They keep going until a whole pass needs no swaps, and count the passes.
Open these notes on screenScan the code, or go to tutorpip.com.