All algorithms
Searching

Linear Search

Check every element until you find it — the baseline every other search beats.

TimeO(n)SpaceO(1)CategorySearching

Linear Search walks the array from the start and compares each element to the target, stopping at the first match. It needs no preparation at all — the data can be in any order, unsorted and unindexed.

That is exactly why it matters as a baseline: Binary Search is faster but demands sorted input, and hash lookups demand a built table. When the data is small or used once, the O(n) scan is genuinely the right answer.

Seeing it next to Binary Search on the same array is the clearest way to feel the difference between O(n) and O(log n) — one pointer crawls, the other leaps.

The code

linear_search.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {5, 2, 9, 1, 7, 3};
    int target = 7;
    int found = -1;

    for (int i = 0; i < (int)a.size(); i++) {
        if (a[i] == target) {
            found = i;
            break;
        }
    }

    cout << found << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Linear Search

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going