Quarry School

Count comparisons in a linear search

Subject: Computing
Level 1 · FoundationsAbout 5 min read3 new terms
How this was estimated

Programmatic estimate. Rung levels, worked steps, prerequisites, terms and sentence length contribute to this level. It describes the lesson, not your ability.

Reading counts the whole lesson, including folded explanations, at 180 words a minute. Practice allows two minutes per item. These are planning assumptions; take the time you need.

AI estimate unavailable.

Path to here

Open the unit’s lesson list to follow the lesson order.

    Leans on

    Quick review (2 minutes)

    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.