Quarry School

Keep a sorted interval for binary search — quick review

In plain words

Someone thinks of a whole number from a known range and answers each guess with higher, lower or correct.

Rule

Binary search works only on a sorted row. Each check compares the target with the middle card of the interval: a match ends the search, and otherwise the interval keeps only the half that can still hold the target. When the interval is empty, the target is not in the row.

Step

  1. Check that the row is sorted, smallest first. If it is not, binary search cannot be used.

  2. This lesson numbers positions from 1: write low = 1 and high = the number of cards, so the interval starts as the whole sorted row.

  3. If low is greater than high, the interval is empty: announce not found and stop.

  4. Work out middle = (low + high) / 2, rounded down: (1 + 2) / 2 is 1.5, which rounds down to 1. Read the card at that position. The search starts at the middle of the interval.

  5. Compare the target with that card and count 1 check: on a match, announce found at position middle and stop. For a smaller target write high = middle - 1, for a larger target write low = middle + 1, and go back to the third step.

Trap

Binary search on a row that is not sorted can miss a target that is there. In the row 9 2 7 4 5, a search for 4 reads the middle card 7, keeps positions 1 to 2 because 4 is smaller, reads the 9, and ends with not found, though the 4 sits at position 4.