Arrays and Iteration
Linear Search
Inspect each element in order and return the first matching index. If the
scan completes without a match, return -1. Demonstrates the early-return
pattern and the not-found fall-through.
Algorithm
The canonical found run uses target = 9, which lives at index 3. The
spec's second canonical run (target = 2) walks the full array and falls
through to -1.
early return
Stop scanning the moment a match is found.
Basic Implementation
basic.py
Replay: real traced execution (multi-file project)
arr = [4, 7, 1, 9, 3, 8]
target = 9
result = -1
for i in range(len(arr)):
if arr[i] == target:
result = i
break
print(result)
arr ← [4, 7, 1, 9, 3, 8]
1arr = [4, 7, 1, 9, 3, 8]2target = 9values this step[4, 7, 1, 9, 3, 8]arrtarget ← 9
1arr = [4, 7, 1, 9, 3, 8]2target = 93result = -1values this step9target[4, 7, 1, 9, 3, 8]arrresult ← -1
2target = 93result = -14for i in range(len(arr)):values this step-1result9targetmatch ← no
4for i in range(len(arr)):5 if arr[i] == target:6 result = ivalues this stepnomatch0i4arr[i]9target-1resultmatch ← no
4for i in range(len(arr)):5 if arr[i] == target:6 result = ivalues this stepnomatch1i7arr[i]9target-1resultmatch ← no
4for i in range(len(arr)):5 if arr[i] == target:6 result = ivalues this stepnomatch2i1arr[i]9target-1resultmatch ← yes
4for i in range(len(arr)):5 if arr[i] == target:6 result = ivalues this stepyesmatch3i9arr[i]9target-1resultresult ← 3
5if arr[i] == target:6 result = i7 breakvalues this step-1 → 3resultstdout ← 3
7 break8print(result)values this step3stdout3result
Complexity
- Time: O(n) worst case
- Space: O(1)
Implementation notes
- Python: write the explicit
for i in range(len(arr))form andbreakafter assigningresult = i. Callingarr.index(target)would hide the index walk. - The replay shows
i,arr[i], and the boolean match result on every step, matching the lesson spec's state-transition table for the found-case run.