Linear (sequential) search compares the key with each element in turn. It needs no sorting, works on arrays and linked lists, and is O(n) worst case. For short or unsorted data it is often the best choice. Small variations find the last match, count matches, or stop early.
Remember
for (int i = 0; i < n; i++)
if (a[i] == key) return i;
return -1;
Reference
Cheat Sheet
Keep these facts handy while you work with Linear Search in C.
Topic
Detail
Time
O(n)
Space
O(1)
Requires
Nothing (unsorted OK)
Variants
First, last, count
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Binary Search.
Example 1 — First, last, count, and miss
The array contains 2 twice.
C
#include <stdio.h>
int main(void) {
int a[] = {4, 2, 7, 2, 9};
int n = 5, key = 2;
int first = -1, last = -1, count = 0;
for (int i = 0; i < n; i++) {
if (a[i] == key) {
if (first < 0) first = i;
last = i;
count++;
}
}
printf("first %d at index %d\n", key, first);
printf("last %d at index %d\n", key, last);
printf("occurrences of %d: %d\n", key, count);
int missing = 5, pos = -1;
for (int i = 0; i < n; i++) if (a[i] == missing) { pos = i; break; }
printf("search %d: %d\n", missing, pos);
return 0;
}
Output
first 2 at index 1
last 2 at index 3
occurrences of 2: 2
search 5: -1
How It Works
One pass tracks the first match, the last match, and the count.
The final loop stops at the first match using break.
A missing key leaves the result at -1 after scanning everything.
Edge Cases & Pitfalls
Check these before relying on Linear Search in real programs.
early
Forgetting to stop
Without break or return, the loop scans the rest of the array needlessly.
type
Comparing strings with ==
For strings use strcmp, not ==.
Remember
Key Takeaways
Simple and general.
O(n) time.
Good for small or unsorted data.
One line: Linear (sequential) search compares the key with each element in turn.
Frequently Asked Questions
When the data is unsorted, small, or you search only once, so sorting would cost more than it saves.
O(n) in the worst and average cases, and O(1) in the best case.
Continue with "C Binary Search" next. Trace how binary search narrows the range in O(log n). The C Searching Algorithms hub lists every topic in order.