Skip to content
Exit presentation

Programming Proper II: Functions, Lists & Simple Algorithms

The whole sort, written down

One pass puts one crate in place. A whole register needs more. A crate is in place when it sits at its final position.

Arrival order: 26, 41, 18, 33, 12.
Step 1 of 6
  1. Arrival order: 26, 41, 18, 33, 12.
  2. Pass 1 places the smallest: 12.
  3. Pass 2 places the next: 18.
  4. Pass 3 places the next: 26.
  5. Pass 4 places the next: 33.
  6. The last crate, 41, is now in place too.

The rule

Repeat the pass. Each pass puts the smallest of the rest in place. Sorting a copy keeps the original.

Five crates need four passes. Once four crates are in place, the fifth is too. Only one place is left, so the last crate fits it.

The passes make 4, then 3, then 2, then 1 comparisons. That is 10 in all. For n crates, the total is n × (n − 1) ÷ 2.

Here order is the list being sorted. place is the position to fill. look is the position being checked.

`` function selectPass(order, place) { let best = place; for (let look = place + 1; look < order.length; look = look + 1) { if (order[look] < order[best]) { best = look; } } const temp = order[best]; order[best] = order[place]; order[place] = temp; } ``

The pass fills one place with the smallest of the rest. The sort repeats it for each place.

`` function sortByWeight(weights) { const order = []; for (let i = 0; i < weights.length; i = i + 1) { order.push(weights[i]); } for (let place = 0; place < order.length - 1; place = place + 1) { selectPass(order, place); } return order; } ``

The sort copies the weights into order, so the original stays. Then it runs one pass for each place except the last. Take board as the arrival list. sortByWeight(board) gives [12, 18, 26, 33, 41]. The board still reads [26, 41, 18, 33, 12]. The sort worked on a copy.

Move the best marker to the smallest crate of the rest. Then swap it to the front. Do this for every pass.

Loading lab…

Jump to lesson

This track

  1. 0 Start here
  2. 1 Is it there at all?
  3. 2 The counted loop
  4. 3 In order first
  5. 4 Counting both searches
  6. 5 One pass, and the box in the middle
  7. 6 The whole sort, written down
  8. 7 Sort once, search many
  9. 8 How the count grows
  10. 9 The big picture
  11. 10 Track quiz

Other tracks