Linear search
Check every element in turn until the key is found.
Syllabus says: “Searching Techniques: Linear Search”
On this page · 11 sections
Check one by one from the start. Found → return index; end reached → −1. Works on ANY array.
Looking for your friend's slippers outside a temple: you check every pair one by one.
Linear search compares the key with each element in turn until a match is found or the list ends; it takes O(n) time and needs no ordering.
Learning objectives
- Write linear search.
- Count comparisons in the best, worst and average case.
Definition
Linear (sequential) search compares the key with a[0], a[1], … in order and returns the first index where they match, or −1 if no element matches.
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm / pseudocode
- 1LinearSearch(a, n, x)
- 2for i ← 0 to n − 1: if a[i] = x
- 3return i
- 4return −1
C implementation
linear_search.ctested ✓ 150/150 cases/* Linear search — KTU PCCST303, Module 4
* Input : n, then n integers, then the key
* Output: index of the first occurrence (-1 if absent) and comparisons. */
#include <stdio.h>
#define MAX 100
int linearSearch(int a[], int n, int key, int *comparisons) {
*comparisons = 0;
for (int i = 0; i < n; i++) {
(*comparisons)++;
if (a[i] == key) return i;
}
return -1;
}
int main(void) {
int n, a[MAX], key, c;
if (scanf("%d", &n) != 1 || n < 0 || n > MAX) { printf("Invalid n\n"); return 1; }
for (int i = 0; i < n; i++)
if (scanf("%d", &a[i]) != 1) { printf("Invalid input\n"); return 1; }
if (scanf("%d", &key) != 1) { printf("Invalid key\n"); return 1; }
int idx = linearSearch(a, n, key, &c);
printf("RESULT: %d\nCOMPARISONS: %d\n", idx, c);
return 0;
}
Sample run · search for 22 · real output from gcc
Input (stdin)
8 45 33 56 22 76 78 40 30 22
Output (stdout)
RESULT: 3 COMPARISONS: 4
Complexity
| Case | Comparisons | Time |
|---|---|---|
| Best (key at a[0]) | 1 | O(1) |
| Worst (last or absent) | n | O(n) |
| Average (successful, equally likely) | (n + 1)/2 | O(n) |
Advantages and disadvantages
- Works on unsorted data and on linked lists.
- Slow for large n compared with binary search or hashing.
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
Sequential scan; O(n) worst/average, O(1) best; no precondition.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §7.2
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)