Lecture Notes — Lecture 17: Searching and Linear Scans

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

Scan first, cleverness later. A linear scan is always available, always correct, and the baseline every faster method must beat. Students who can write a clean scan can debug anything fancier.

Early exit is a correctness question too. Stopping early must be justified: found the first match (scanning order guarantees it), or a monotone property proves nothing ahead can match. Unjustified exits are bugs.

Sentinels are contracts. Returning -1 for 'not found' collides with real data unless the spec forbids negatives; returning None is safer in Python. The class debates which convention the spec should pin.

Preconditions unlock speed. The two-sorted-halves case: knowing the structure, the minimum sits at the run boundary - check two candidates instead of n. The scan still exists as the fallback when the promise fails.

Counting the cost. Best case 1 step, worst n, average n/2 for a found target. On 10^6 items that is real time; on 10 it is irrelevant - students learn when the distinction matters.

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. Scan is the baseline; speed requires a precondition you can verify.
  2. Early exit needs a reason: found-first or proof-nothing-ahead.
  3. Sentinel answers are contracts written in the spec.
  4. Best/worst case is a range; know which matters at your input size.

Practice questions

Where this leads

Next lecture: Sorting as an Idea. The quiz below checks this lecture's essentials before we build on them.