Quarry School

Count comparisons in a linear search — quick review

In plain words

A box of ticket stubs sits in no particular order, and you need one particular stub.

Rule

A linear search checks the cards in order and stops at the first card that shows the target, or after the last card. It makes one comparison for each card it checks: one when the target is first, and as many as there are cards when its first match is the last card or it is not in the row.

Step

  1. Write the row and the target.

  2. Compare the target with the first card and count 1.

  3. If the card does not match and a card is left after it, move to the next card, compare and add 1 to the count. Repeat until a card matches or no card is left.

  4. Announce the result: the position of the first matching card, or not found after the last card.

  5. Check the count: it equals the position of the matching card, or the number of cards when nothing matched.

Trap

A linear search that stops early cannot say not found. If you check three cards of 7 3 9 4 for the target 4 and stop, the 4 on the last card is missed. A linear search says not found only after the last card.

When the target appears twice, the search stops at the first one. In the row 6 2 8 2 5, a search for 2 stops at position 2 after two comparisons and never reaches the second 2.