6. Linear Search
π§Έ ELI5: You lost your favorite toy car in a toy box full of 50 toys. You pick up toy #1, check if it's the car, put it down, pick up toy #2, check... You keep going until you find it. No shortcuts.
π Real life: Scanning every song in an unsorted playlist looking for one title. Checking every locker in a hallway for your friend's name because lockers aren't sorted by name.
π Pseudocode:
function linearSearch(list, target):
for i from 0 to length(list) - 1:
if list[i] == target:
return i
return -1
πΉ Go:
package main
import "fmt"
func linearSearch(toys []string, target string) int {
for i, toy := range toys {
if toy == target {
return i
}
}
return -1
}
func main() {
toys := []string{"ball", "robot", "car", "doll"}
fmt.Println(linearSearch(toys, "car")) // 2
}
π¨ C:
#include <stdio.h>
#include <string.h>
int linear_search(const char *toys[], int n, const char *target) {
for (int i = 0; i < n; i++) {
if (strcmp(toys[i], target) == 0) return i;
}
return -1;
}
int main(void) {
const char *toys[] = {"ball", "robot", "car", "doll"};
printf("%d\n", linear_search(toys, 4, "car")); // 2
return 0;
}
β±οΈ Complexity: O(n) β worst case, you check every single toy.