Linear Search

Context: FIT1008_MOC · the baseline sequential search · contrast with Binary Search and Hash Table

Quick Revision

  • 🎯 Objective: scan elements one by one until match or end ➔ , but works on any Iterable with no precondition.
  • 📦 Core Components: walk sequence ➔ compare each ➔ return index / sentinel.
  • ⚡ Key Constraint: comparisons — no order, no random access needed, so it’s the only option for unsorted data or a LinkList.

📝 Core

1. The Algorithm (Scan Until Found)

  • Mechanism ➔ visit each element in order, compare to target, stop on match (return index) or exhaust (return sentinel/raise).
  • No precondition ➔ needs neither order nor random access ➔ works on any Iterable, including a singly-linked LinkList.

2. Cost: Decrease-by-One Recurrence

  • Recurrence ➔ check one, recurse on the rest ➔ .
  • Bounds ➔ best (first element), worst/avg (last / absent).

3. “Linear Relative to the Reference”

  • Reference mattersnaive(k) guessing is in the value but in its bit-length ().
  • Lesson ➔ always state complexity relative to input size — “linear” is meaningless without naming the reference.

⚙️ Core Implementation

🔹 linear_search (sequential scan)

⚖️ Core Decision Matrix

SearchTime (worst)PreconditionStructure
Linearnoneany Iterable (incl. LinkList)
Binary Searchsorted + accessarray
Hash Table expectedgood hash, no orderhash array

When It Flips: binary/hash search beat linear asymptotically, but linear is the only option when data is unsorted or lacks random access (linked structures). For one-off searches on tiny/unsorted data, linear's setup wins over sorting first ().

📊 Exam Execution Trace

Manual Execution Trace

Search 23 in [2,5,8,12,15,23,42,50]:

Step / StateTrigger Opiarr[i]Action
0 (Init)init
1compare02≠ → advance
compare1–45,8,12,15≠ → advance
5compare523match → return 5

Applied Exercise

Problem: Derive the worst-case bound from the decrease-by-one recurrence. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: worst/average — one comparison per element, no shortcut without a precondition.

🧠 Active Recall