Linear Search
The simplest search: check the elements one by one from start to end.
#How does it work?
Linear search starts at the beginning and checks the elements one by one to find the target. If it finds it, it returns the index; if it reaches the end, the value isn't there.
It is the simplest search and doesn't need sorted data. It works on anything you can walk through in order: arrays, linked lists, lines of a file.
The price is time: in the worst case (the value is last or missing) every element has to be checked.
#Live animation
Target: 24. We'll start at the beginning and check the elements one by one.
for i = 0 to n - 1if a[i] == target: return ireturn -1
#Step by step
- 01Start at the first element.
- 02Compare the element with the target.
- 03If they are equal, return its index and stop.
- 04Otherwise move to the next element.
- 05If you reach the end, the value isn't there; return -1.
#Example code
The same algorithm in 8 languages. Every program is compiled, run and checked to print the same output.
def linear_search(a: list[int], target: int) -> int:
"""Returns the index of the first element equal to target, or -1."""
for i, value in enumerate(a):
if value == target:
return i
return -1
numbers = [4, 8, 1, 9, 3]
print(linear_search(numbers, 9))
print(linear_search(numbers, 7))#Complexity
| Best | O(1) |
|---|---|
| Average | O(n) |
| Worst | O(n) |
| Extra memory | O(1) |
| Needs sorted data? | No |
If the value is first, one comparison is enough. On average half of the elements are checked, and all of them if the value is missing. If data is sorted once and searched many times, binary search is much faster.
#When to use it?
The right choice for small or unsorted data, one-off searches, and structures without indexed access such as linked lists. Functions like indexOf, includes and find in programming languages do a linear search.
#Practice
Log in to answer questions and save your progress.
Easy
Does linear search require sorted data?
- 1No
- 2Yes
What is linear search's worst-case complexity?
- 1O(n)
- 2O(1)
- 3O(log n)
- 4O(n²)
How many comparisons are made if the target is the first element?
- 11
- 2n
- 3n / 2
- 4log n
Medium
Searching for 3 in [7, 3, 9, 3, 5], which index does linear search return?
- 11
- 23
- 30
- 4-1
Hard
In which case must you use linear search instead of binary search?
- 1Searching an unsorted linked list
- 2Searching a sorted array many times
- 3Looking up a word in a dictionary
- 4Searching a sorted database index
#Up next
Lessons that build on this one: