Linear Search
Find a target in unsorted data.
What is Linear Search?
Linear search checks each item until it finds a match or reaches the end.
Important points
- Test empty, single-element, duplicate, and already sorted inputs.
- Separate correctness from optimization.
- Use the standard library in production unless a custom implementation is justified.
Linear Search visualizer
O(n)Use Play or Step to follow each comparison and data movement.
C and C++ code examples
#include <stdio.h>
int find(const int *values, int size, int target) {
for (int index = 0; index < size; ++index) {
if (values[index] == target) return index;
}
return -1;
}
int main(void) {
int values[] = {14, 3, 27, 8, 19};
printf("index=%d\n", find(values, 5, 8));
}
index=3
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector values{14, 3, 27, 8, 19};
auto match = std::find(values.begin(), values.end(), 8);
std::cout << "index="
<< std::distance(values.begin(), match) << '\n';
}
index=3
C and C++ comparison
Both implementations run in O(n) worst-case time. C returns a signed index so -1 can mean not found; C++ returns an iterator and compares it with end.
Loops, pointers, lengths, and temporary buffers are written explicitly.
Iterators and standard algorithms separate operations from container representation.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Trace each comparison on paper.
- Test duplicates and extreme values.
- Benchmark the custom implementation against the standard library.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges