It works on any list#
Linear search never uses the order of the list. It checks each number from the left, so it works on a shuffled list just as well as a sorted one, and it stops at the first match.
Quick check
Quick check: You search these marks for 48. Which index does linear search return?
The code#
The same idea, as code. Slide the target to 5, a number that is not in the list, and watch it check every one before giving up.
target- nums = [4, 2, 7, 1, 9, 3]
- target = 9
- answer = -1
- for i in range(len(nums)):
- if nums[i] == target:
- answer = i
- break
- print(answer)
Variables
nums
Six numbers, in no particular order.
The same function in Python, C++, C, Java and Go:
How long it takes#
The worst case is a target that is last, or not there at all: every number gets checked. Double the list and you double the checks. That is O(n) time, with O(1) extra space.
Quick check
Quick check: A list holds 10 lakh roll numbers, and the one you want is not in it. How many checks does linear search make?
When to use it#
| Situation | Use |
|---|---|
| The list is not sorted | Linear search |
| The list is sorted and large | Binary search |
| The list is tiny | Linear search, it is simpler |
| You want the first item that matches a condition | Linear search |
What to remember#
- Check each item from the left; stop at the first match, or return -1 at the end.
- Works on any list, sorted or not.
- O(n) time and O(1) extra space.