Visualizer › Searching
Linear Search
Checks every element from left to right until it finds the target or reaches the end.
How it works
- Works on any array — sorted or not.
- The only option for unsorted data without extra memory.
- For many searches, sort once and use binary search, or use a hash set.
Complexity
- Best time: O(1)
- Average time: O(n)
- Worst time: O(n)
- Extra space: O(1)
Code (Python)
def linear_search(a, target):
for i, x in enumerate(a):
if x == target:
return i
return -1Practise: Arrays problems