Linear Search
Read the values one by one until the target turns up or the data runs out. It needs no order and no set-up, and it costs one comparison per value it passes.
How Linear Search Works
- Start at index 0.
- Compare the element with the target. If they are equal, return the index.
- Otherwise move to the next index.
- If the index passes the last element, return -1: the target is absent.
Linear search, also called sequential search, looks at each element in order and compares it with the target. The first element that matches ends the search and its index is returned. If the loop reaches the end without a match, the value is not there and the search returns -1.
On the array 3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80, finding 69 means rejecting 13 values before reaching index 13: 14 comparisons. The same array appears in the jump search, interpolation search, exponential search and ternary search lessons, so the comparison counts can be set side by side.
- Empty array: the loop never runs, so the answer is -1 at once
- With duplicates it returns the first match; scan from the end for the last one
- It only needs an equality test, so it works on values that cannot be ordered
Linear Search Time Complexity
The cost is the number of comparisons, and that depends only on where the target sits. The value at index k costs k + 1. The best case is the first element, one comparison. Averaged over every position, a value that is present costs (n + 1) / 2, which is 8.5 on the 16-value array.
A miss is always the worst case: n comparisons, because without order any unread element might still be the target. Both the average and the worst case grow in step with n, so linear search takes O(n) time. The loop keeps only an index, so the extra space is O(1).
| Case | Example | Comparisons | Growth |
|---|---|---|---|
| Best | target 3 at index 0 | 1 | O(1) |
| Average hit | any present value | 8.5 | O(n) |
| Late hit | target 69 at index 13 | 14 | O(n) |
| Miss | target 50 | 16 | O(n) |
- Doubling the array doubles both the average and the worst case
- The order of the data never changes the bound, only which values are cheap
Sentinel Linear Search
A plain loop makes two checks for every element: is the index still in range, and is this element the target? On a miss over 16 values that is 16 equality tests plus 17 range tests, 33 in all.
Sentinel linear search puts a copy of the target in one extra slot after the last element. The loop is now certain to stop, so it can drop the range test and only check for equality. One last test after the loop asks whether it stopped on the sentinel, which means the target was absent. The miss now costs 17 + 1 = 18 tests.
The bound is still O(n); what shrinks is the constant factor, because the loop body has one branch instead of two. The trick needs a writable spare slot, and the array must be restored afterwards. It is unsafe when another thread reads the same array at the same time.
- Saves one branch per element, not any comparisons with the target
- Needs a spare writable slot, and the original value put back
- Many compilers already unroll or vectorise a plain scan, so measure first
Terms, operations, and practical uses
Key terms
- Sequential searchAnother name for linear search: elements are examined one after another.
- SentinelA copy of the target placed after the data so the loop is sure to stop.
- Self-organising listA list that moves found elements forward so frequent searches get cheaper.
Related
- Searching algorithmsLinear, binary, hash and tree search compared.
- Binary searchO(log n) search on sorted, indexable data.
- Jump searchSkip ahead in blocks on sorted data, then scan one block.
- Contains DuplicateA problem where a scan with a set replaces nested scans.
Code in Python, C++ and Java
def linear_search(a, target):
checks = 0
for i, x in enumerate(a):
checks += 1
if x == target:
return i, checks
return -1, checks
def sentinel_search(a, target):
n = len(a)
a.append(target)
tests = 0
i = 0
while True:
tests += 1
if a[i] == target:
break
i += 1
a.pop()
tests += 1
return (i if i < n else -1), tests
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
nums = [3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80]
mixed = [47, 3, 74, 21, 58, 12, 80, 33, 7, 69, 27, 64, 18, 42, 53, 38]
for target in (69, 50):
i, checks = linear_search(nums, target)
print(f"sorted, find {target}: index {i}, {checks} comparisons")
i, checks = linear_search(mixed, 69)
print(f"unsorted, find 69: index {i}, {checks} comparisons")
print(f"binary search on unsorted, find 69: index {binary_search(mixed, 69)}")
_, checks = linear_search(nums, 50)
_, tests = sentinel_search(nums, 50)
print(f"miss: plain loop {checks} + {checks + 1} = {2 * checks + 1} tests, sentinel {tests} tests")#include <iostream>
#include <utility>
#include <vector>
using namespace std;
pair<int, int> linearSearch(const vector<int>& a, int target) {
int checks = 0;
for (int i = 0; i < (int)a.size(); i++) {
checks++;
if (a[i] == target) return {i, checks};
}
return {-1, checks};
}
pair<int, int> sentinelSearch(vector<int>& a, int target) {
int n = a.size(), tests = 0, i = 0;
a.push_back(target);
while (true) {
tests++;
if (a[i] == target) break;
i++;
}
a.pop_back();
tests++;
return {i < n ? i : -1, tests};
}
int binarySearch(const vector<int>& a, int target) {
int lo = 0, hi = a.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
int main() {
vector<int> nums = {3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80};
vector<int> mixed = {47, 3, 74, 21, 58, 12, 80, 33, 7, 69, 27, 64, 18, 42, 53, 38};
for (int target : {69, 50}) {
auto [i, checks] = linearSearch(nums, target);
cout << "sorted, find " << target << ": index " << i << ", " << checks << " comparisons\n";
}
auto [i, checks] = linearSearch(mixed, 69);
cout << "unsorted, find 69: index " << i << ", " << checks << " comparisons\n";
cout << "binary search on unsorted, find 69: index " << binarySearch(mixed, 69) << "\n";
int miss = linearSearch(nums, 50).second;
int tests = sentinelSearch(nums, 50).second;
cout << "miss: plain loop " << miss << " + " << miss + 1 << " = " << 2 * miss + 1
<< " tests, sentinel " << tests << " tests\n";
}import java.util.ArrayList;
import java.util.List;
public class Main {
static int[] linearSearch(int[] a, int target) {
int checks = 0;
for (int i = 0; i < a.length; i++) {
checks++;
if (a[i] == target) return new int[]{i, checks};
}
return new int[]{-1, checks};
}
static int[] sentinelSearch(List<Integer> a, int target) {
int n = a.size(), tests = 0, i = 0;
a.add(target);
while (true) {
tests++;
if (a.get(i) == target) break;
i++;
}
a.remove(a.size() - 1);
tests++;
return new int[]{i < n ? i : -1, tests};
}
static int binarySearch(int[] a, int target) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] nums = {3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80};
int[] mixed = {47, 3, 74, 21, 58, 12, 80, 33, 7, 69, 27, 64, 18, 42, 53, 38};
for (int target : new int[]{69, 50}) {
int[] r = linearSearch(nums, target);
System.out.println("sorted, find " + target + ": index " + r[0] + ", " + r[1] + " comparisons");
}
int[] r = linearSearch(mixed, 69);
System.out.println("unsorted, find 69: index " + r[0] + ", " + r[1] + " comparisons");
System.out.println("binary search on unsorted, find 69: index " + binarySearch(mixed, 69));
List<Integer> list = new ArrayList<>();
for (int x : nums) list.add(x);
int miss = linearSearch(nums, 50)[1];
int tests = sentinelSearch(list, 50)[1];
System.out.println("miss: plain loop " + miss + " + " + (miss + 1) + " = " + (2 * miss + 1)
+ " tests, sentinel " + tests + " tests");
}
}Step through it
Running on [3, 7, 12, 18, 21, 27, 33, 38, 42, 47, 53, 58, 64, 69, 74, 80] · target 69
When a Scan Is the Right Choice
Linear search is the only correct method when the data has no order. Shuffle the same 16 values and it still finds 69, now at index 9 after 10 comparisons. Binary search on the shuffled array reads 33, 64, 42, 53 and 38, always moving right, and reports -1 while 69 sits in the half it discarded: wrong, not just slow.
It is also the only option without random access. A linked list cannot jump to its middle, so even a sorted list is scanned node by node. A stream that can be read once, such as lines arriving from a file or a socket, allows nothing else.
On small arrays a scan is often the fastest choice in practice, up to a few dozen elements. It reads memory in order, which caches and prefetchers handle well, and its single branch is easy for the processor to predict. Sorting first pays off only when the same data is searched many times; the searching algorithms lesson works out where that point lies.
- Unsorted data searched once or twice: scan it
- Linked lists and one-pass streams: a scan is the only option
- Large sorted arrays searched often: use binary search instead
Useful Variations
Last match: run the loop from the end. All matches: keep going after a hit and collect every index; this always costs n. Count: the same loop with a counter instead of a return.
Early exit on sorted data: if the values are known to be ascending, stop as soon as an element is larger than the target. Searching for 50 then stops at 53 after 11 comparisons instead of 16. It is still O(n), and it is the first step towards the ideas behind jump search.
Self-organising lists: when some values are searched far more often than others, move each found element to the front, or swap it one place forward. Popular values drift towards index 0 and become cheap to find.
- Scanning from the end finds the last occurrence
- On sorted data, stopping at the first larger value shortens misses
- Move-to-front makes frequently searched values cheaper