Arrays and Iteration
Linear Search
Walk an array once looking for a target value. Return the index of the
first match, or -1 if none. The simplest possible search loop.
Algorithm
Canonical input arr = [4, 7, 1, 9, 3, 8] with target = 9 finishes
after four compares; the matching index is 3.
early exit
Return the index the moment `arr[i]` equals the target. Walking past it would defeat the point.
sentinel return
A no-match walk falls off the loop and returns `-1`.
Basic Implementation
basic.ts
Replay: real traced execution (multi-file project)
const arr: number[] = [4, 7, 1, 9, 3, 8];
const target: number = 9;
function linearSearch(arr: number[], target: number): number {
for (let i: number = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
const result: number = linearSearch(arr, target);
console.log(result);
arr ← [4, 7, 1, 9, 3, 8]
1const arr: number[] = [4, 7, 1, 9, 3, 8];2const target: number = 9;values this step[4, 7, 1, 9, 3, 8]arrtarget ← 9
1const arr: number[] = [4, 7, 1, 9, 3, 8];2const target: number = 9;3function linearSearch(arr: number[], target: number): number {values this step9target[4, 7, 1, 9, 3, 8]arrresult ← -1
10}11const result: number = linearSearch(arr, target);12console.log(result);values this step-1result9targetmatch ← no
4for (let i: number = 0; i < arr.length; i++) {5 if (arr[i] === target) {6 return i;values this stepnomatch0i4arr[i]9targetmatch ← no
4for (let i: number = 0; i < arr.length; i++) {5 if (arr[i] === target) {6 return i;values this stepnomatch1i7arr[i]9targetmatch ← no
4for (let i: number = 0; i < arr.length; i++) {5 if (arr[i] === target) {6 return i;values this stepnomatch2i1arr[i]9targetmatch ← yes
4for (let i: number = 0; i < arr.length; i++) {5 if (arr[i] === target) {6 return i;values this stepyesmatch3i9arr[i]9targetresult ← 3
5if (arr[i] === target) {6 return i;7}values this step3result3istdout ← 3
11const result: number = linearSearch(arr, target);12console.log(result);values this step3stdout3result
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- TypeScript: explicit
for (let i: number = 0; i < arr.length; i++). Never usearr.indexOf(target)— the lesson is teaching the walk. - Function signature
linearSearch(arr: number[], target: number): numberdocuments the integer-array contract. - The replay shows the running index, the element being checked, and a
matchindicator on each frame.