Linear Search
Linear search checks each item until it finds a match or reaches the end.
What is Linear Search?
Linear search checks each item until it finds a match or reaches the end.
Find a target in unsorted data.
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
main.c
#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
C++
main.cpp
#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.
C
Loops, pointers, lengths, and temporary buffers are written explicitly.
C++
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.