Quarry School

Trace a sort on repeated keys — quick review

In plain words

Sorting a hand of cards by picking out the smallest, then the smallest of the rest, and so on, shows the idea of this lesson.

Rule

Selection sort moves the smallest unsorted card to the sorted row, pass after pass, until no unsorted card is left, and finding the smallest of n unsorted cards takes n - 1 comparisons. With this lesson's rules, a card replaces the smallest so far only if its key is smaller, and the cards left unsorted keep their order; then the leftmost of equal smallest cards moves first, and equal keys keep their order.

Step

  1. Write the unsorted row with each card told apart, and an empty sorted row.

  2. Mark the first unsorted card as the smallest so far.

  3. Compare the marked card with each later unsorted card in turn, counting each comparison. When a card's key is smaller than the marked card's key, move the mark to that card, and compare the cards after it with the newly marked card.

  4. Move the marked card to the end of the sorted row, and close up the unsorted row without changing its order.

  5. Repeat until no unsorted card is left, then add up the comparisons.

Trap

One word changes the order of equal keys. If the mark switched to a card that is smaller or equal, pass 3 would move the blue 4 first, and the sorted row would end blue 4, red 4. Both rows are sorted by key, but only one keeps the start order of the fours. Write the test you mean.

A second slip is comparing against cards already sorted. Each pass compares only unsorted cards, which is why the count falls by one each pass.