Skip to main content
CodeFlow
all algorithms
algorithm 03

Linear Search

The honest, lazy way: check every element until you find the target. No prep, no sorting needed — but slow on big lists.

03 / Linear Search

Find target in unsorted list

42017188273355431596624761889791013114712921336146815
comparisons
0
index
result
step 0
  1. 0def linear_search(arr, target):
  2. 1 for i in range(len(arr)):
  3. 2 if arr[i] == target:
  4. 3 return i
  5. 4 return -1
Click Search. Try the existing target, or shuffle for a fresh array.

What you just watched

Linear search has one move and runs it on a loop: look at the next item; if it's the one I want, stop; otherwise keep going. The for-loop is the engine, the comparison is the decision (which we covered in Conditions). That's the whole algorithm.

On a 16-element list, the worst case is 16 comparisons — about as cheap as algorithms come. On a million-element list, the worst case is a million comparisons, and you'll feel it. That's where Binary Search comes in (sorted lists only).

Try a target that doesn't exist in the array (e.g., 999) and watch the algorithm sweep all 16 cells before giving up. That's the worst case made visible.