Algoritmalar

Linear Search

Searching O(n) O(1)

Walks the array element by element until the target is found — works on any array, sorted or not.

max 16 numbers (0–999)
Idle
23
7
41
15
3
34
9
28

Scanning 8 elements for 15.

InvariantEvery index before i has been checked and is not the target.

1/6
probes0i0
linear-search.c
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target)
return i;
}
return -1;
}

Walk the array front to back and compare each element with the target until you hit it or run out.

Best case

Target is the first element: O(1).

Worst case

Target is last or absent: O(n).

When to use it

Unsorted or tiny arrays, linked lists, or when you search only once so sorting wouldn't pay off.