Quick Answer

Linear search checks items in order until a match appears. This post shows 3 approaches. They are the basic scan, find all matches and sentinel search. Worst case time is O(n). Space is O(1). Sorted data is not needed. Python and C++ code below was executed.

Linear search is the first search algorithm most learners meet. It is also a search you do in real life. Checking pockets one by one for your keys is linear search.

It looks plain yet one case exists where it beats fancier searches. Sections below trace one example and show 3 approaches with tested code.

You check every item in order. Start at the first item and compare it to the value you want. Matching ends the search and a mismatch moves you to the next item.

Nothing needs setup. Items can sit in any order. Sorted data is not required which is not true of binary search.

Python's own list.index scans the same way. According to the Python tutorial it returns the position of the first match and raises ValueError when the value is missing.

How Does Linear Search Work Step by Step?

Take the array 4, 2, 7, 1, 9 and search for 7. Three steps follow.

  • Compare the current item. Index 0 has 4 and that is not 7.
  • Stop at the first match. Index 1 has 2. Index 2 has 7 so the search ends after 3 checks and reports position 2.
  • Return -1 at the end. Searching for 5 checks all 5 items and returns -1.

Output below comes from the tested trace function.

[4, 2, 7, 1, 9] find 7 -> position 2 after 3 checks
[4, 2, 7, 1, 9] find 5 -> position -1 after 5 checks
[8, 3, 5, 9, 1] find 9 -> position 3 after 4 checks

Last two items were never checked in the first search. That early stop explains why speed depends on where the value sits.

How Do You Code the Search in Python and C++?

Approach #1: Basic Scan

What you get. First matching position or -1. Python version below returns inside the loop.

def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1


print(linear_search([4, 2, 7, 1, 9], 7))
print(linear_search([4, 2, 7, 1, 9], 5))

C++ version below uses a vector and has the same shape.

#include <iostream>
#include <vector>
using namespace std;

int linearSearch(const vector<int>& arr, int target) {
    for (int i = 0; i < (int)arr.size(); i++) {
        if (arr[i] == target) return i;
    }
    return -1;
}

int main() {
    vector<int> arr = {4, 2, 7, 1, 9};
    cout << linearSearch(arr, 7) << endl;
    cout << linearSearch(arr, 5) << endl;
}

Both versions print 2 and then -1.

Approach #2: Find All Matches

What you get. Every matching position. Scanning continues to the end and collects every index.

def find_all(arr, target):
    return [i for i in range(len(arr)) if arr[i] == target]


print(find_all([3, 8, 3, 5, 3], 3))
print(find_all([3, 8, 3, 5, 3], 9))

Output is [0, 2, 4] for the value 3 and an empty list for 9.

Approach #3: Sentinel Search

What you get. One comparison less per step. You place the search value at the end of the list first so the loop needs no check for the end of the list. Code restores the last item afterwards.

def sentinel_search(arr, target):
    if not arr:
        return -1
    n = len(arr)
    last = arr[-1]
    arr[-1] = target
    i = 0
    while arr[i] != target:
        i += 1
    arr[-1] = last
    if i < n - 1 or last == target:
        return i
    return -1


print(sentinel_search([4, 2, 7, 1, 9], 7))
print(sentinel_search([4, 2, 7, 1, 9], 9))
print(sentinel_search([4, 2, 7, 1, 9], 5))

Output is 2, 4 and -1. Time remains O(n) because the loop still visits items one by one.

Tested. Python 3.13.18 matched the built in list.index on 3,000 random lists including the empty list. Find all matches and sentinel search passed the same lists.

Sentinel search restored the original list every time. g++ 13.3 compiled the C++ version with warnings on and printed 2 and -1. Tests ran in a cloud sandbox.

What Is the Time and Space Complexity?

Time depends on where the value sits. Fastest case is the first item so the search ends in 1 step which is O(1).

Worst case is the last item or a missing value so the search checks all n items which is O(n). Average case lands near the middle of the list.

Space is O(1) because the search needs only a counter. Table below compares worst case checks with binary search on a sorted list.

List sizeLinear search checksBinary search checks
1,0001,00010
1,000,0001,000,00020

Binary search numbers come from the ceiling of log base 2 of n plus 1. Binary search needs sorted data and linear search does not.

When Should You Use Linear Search?

Use it when data is unsorted or the list is small. Use it too when you need only one lookup. Sorting first costs more than one scan.

Test below searched 1,000,000 random integers for the last item. Python loop scan took 0.018 s. Sorting the list and then using binary search took 0.197 s as the lowest of 5 trials in CPython 3.13.18.

Sorting pays off only when many lookups follow. Practice more problems in the array practice set and learn the container in the array lesson.

What Is the Difference in Linear Search vs Binary Search?

This table compares linear search vs binary search on 4 points.

PointLinear searchBinary search
Sorted data neededNoYes
Worst case checksnAbout log base 2 of n
One lookup in 1,000,000 items (tested)0.018 s0.197 s with sorting
Good forUnsorted data and small listsSorted data with many lookups

See time complexity for the notation. Wider context sits in the what is DSA guide.

Frequently Asked Questions

How Many Checks Does Linear Search Need?

It is O(n) in the worst case because every item can be checked. Best case is O(1) if the first item matches and space is O(1).

Does It Need a Sorted List?

No. Linear search works on data in any order. Binary search needs sorted data.

Is Scanning Slower Than Binary Search?

On large sorted lists yes. On one lookup in unsorted data the scan wins. Test result is 0.018 s for the scan against 0.197 s for sorting and then binary search.

When Is a Plain Scan a Good Choice?

Use it for unsorted data, small lists or a single lookup. Sorting first costs more than one scan in those cases.

What Does It Return When the Value Is Missing?

Code above returns -1. Python's list.index raises ValueError instead.

Can It Find More Than One Match?

Yes. Scan to the end and collect every position. Approach #2 above does this.

What Is Sentinel Search?

It is a variant that places the search value at the end of the list first. Loop then needs no end of list check and time remains O(n).

What Should You Remember Before Moving On?

Check items in order and stop at the first match. Report -1 when the end arrives empty handed.

Key takeaways.

  • Linear search works on any list and costs O(n) in the worst case.
  • Space is O(1) and an early match stops the scan.
  • One lookup in unsorted data beats sorting first.

Check yourself. In the array 8, 3, 5, 9, 1 how many checks does the search make to find 9? Answer is 4.