The simplest search algorithm — scan every element one by one. Watch linear search in action, learn when to use it, and compare it with binary search.
// WHAT YOU'LL LEARN
Prerequisites: Basic programming · Arrays · Loops
// DEFINITION
Linear search (also called sequential search) checks each element of an array one by one, from start to end, until it finds the target or reaches the end of the array.
It works on any array— sorted or unsorted. It's the simplest search algorithm, with O(n) time complexity.
// INTERACTIVE VISUALIZER
Set a target, press PLAY, and watch linear search check each element one by one. Try different targets — including ones not in the array!
Press PLAY to start searching!
Comparisons
0
Array Size
9
Result
—
// ALGORITHM WALKTHROUGH
Press PLAY to trace the algorithm through the flowchart.
Press PLAY to step through the algorithm line by line.
// LINEAR VS BINARY
Drag the slider to see how many comparisons each algorithm needs. Binary search requires sorted data — linear search works on anything.
LINEAR SEARCH
1,000
comparisons (worst case)
BINARY SEARCH
10
comparisons (worst case)
For n=1,000, binary search is approximately 100× faster than linear search (on sorted data).
// OPTIMIZATION
Sentinel linear search is an optimization that removes the i < n bounds check from the loop. We place the target at the end of the array, so the loop is guaranteed to find it — we only need one comparison per iteration instead of two.
while (i < n) { // check 1
if (arr[i] == target) // check 2
return i;
i++;
}arr[n-1] = target; // place sentinel while (arr[i] != target) // only 1 check i++; // check if real or sentinel
// RECURSIVE VARIANT
function recursiveSearch(arr, target, i):
if i >= arr.length: // base case: not found
return -1
if arr[i] == target: // base case: found
return i
return recursiveSearch(arr, target, i + 1) // recursive case// COMPLEXITY ANALYSIS
| Case | Time Complexity | Comparisons | Description |
|---|---|---|---|
| Best | O(1) | 1 | Target at first position |
| Average | O(n) | n/2 | Target in the middle |
| Worst (found) | O(n) | n | Target at last position |
| Worst (not found) | O(n) | n | Target not in array |
| Space | O(1) | — | No extra data structures |
// PRACTICE & ASSESS
Now that you've learned the concept, put it into practice. Solve coding problems and take quizzes to reinforce what you've learned.
// TUTORIAL QUIZZES · LEVELS 1–9
Nine progressive quizzes from Level 1 to Level 9. Each has 10 questions with a 10-minute timer. XP scales with level — L1 gives 10 XP, L9 gives 90 XP. Click a quiz to expand and begin.
// REFERENCES
// READY?
Practice 1,000+ coding problems, follow career roadmaps, and get hired.