Skip to content
Your progress

Checking your sign-in…

Who's learning?

Each profile keeps its own read lessons, badges, streak, and practice scores on this device.

Lesson 5 of 11

One pass, and the box in the middle

Show on a big screen

7 min

Text size

Four crates arrived weighing 32, 18, 45 and 24 kg. Put the lightest first. The register lists their weights in arrival order. Best means the lightest crate seen so far. In the code, best holds that crate's position.

Register: 32, 18, 45, 24. Best = 32.
Step 1 of 6
  1. Register: 32, 18, 45, 24. Best = 32.
  2. 18 < 32. Best becomes 18.
  3. 45 is not smaller. Best stays 18.
  4. 24 is not smaller. Best stays 18.
  5. Swap 18 to the front.
  6. Position 0 is sorted.

The rule

Walk the unsorted part. Track the smallest seen so far. Swap it to the front, using a temp box.

This is one pass of selection sort. A pass is one trip through the unsorted part. It selects the smallest, then swaps it into place.

Here kg is the register of crate weights. i is the position being checked. The name temp is a box holding one weight briefly.

`` const n = kg.length; let best = 0; for (let i = 1; i < n; i = i + 1) { if (kg[i] < kg[best]) { best = i; } } let temp = kg[best]; kg[best] = kg[0]; kg[0] = temp; ``

After the pass, the register reads [18, 32, 45, 24]. The pass made 3 comparisons for 4 crates.

The swap needs three lines. Copy 18 into temp. Put 32 where 18 was. Put temp at the front.

Watch out!

Halfway through the swap, the register holds two 32s and no 18. The temp box keeps the 18 safe.

Step through the pass. Watch i, best and temp change.

Loading lab…

Try the lab to finish this lesson.