LINEAR SEARCH
CHECK ONE BY ONE · O(n)
prostudypk.com
Search One by One
key = 42
17
0
✗
8
1
✗
25
2
✗
3
3
✗
61
4
✗
9
5
✗
42
6
✗
30
7
✗
14
8
✗
5
9
✗
for i in range(n):
if a[i] == key:
return i
return -1
Found! index 6
42
target (key)
current index
comparisons
1. Linear Search
Check every item from start to end
Found → return the index, otherwise −1
2. Speed
Best case: 1 comparison
Worst case: n comparisons · O(n)
3. When to Use?
When the list is unsorted
When sorted → binary search
COMPUTER SCIENCE · ALGORITHMS · PUNJAB BOARDS
‹ Labs
↺
❚❚
1×
Next ›