Algorithms

Linear search: one by one, like trying keys on a key ring

Cover of the article Linear search: one by one, like trying keys on a key ring
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does linear search work?
  2. Linear search example, step by step
  3. Linear search in Python, PHP, C and JavaScript
  4. How many comparisons does linear search make?
  5. Now you ask: what is this n?
  6. What measures are used to explain Big O?
  7. Now you ask: is there a search faster than linear search?
  8. Do I have to write linear search every time?
  9. What are the most common mistakes in linear search?
  10. Now it’s your turn!

Linear search is an algorithm that looks for a value by checking the elements one by one, from the first to the last, until it finds it or they run out. It’s also called sequential search.

In the article on recursion, I told you we were on our way to search and sorting algorithms. The time has come! And we’ll start with the simplest search of all.

Think of a bunch of keys you’ve never used. To open the door, you try the first key. Didn’t open? You try the second. And you keep going like that, one by one, until the door opens or the keys run out. You don’t skip any, because nothing on the key ring tells you where the right key is. That’s linear search!!!

Three-panel comic: a person with a bunch of six keys in front of a door tries one key at a time; the first three don’t open it and the fourth one opens the door
Linear search with a bunch of keys: one by one, in order, until the door opens.

How does linear search work?

The algorithm always repeats the same steps:

  • Look at the element in the current position, starting with the first one.
  • If it’s the value you’re looking for, you found it. Return the position and stop.
  • If it isn’t, move on to the next position and repeat.
  • If the positions run out, the value isn’t there.

Notice a detail that makes all the difference: at no step does the algorithm need the data to be in order. Linear search works with the array just the way it is. It’s the simplest search algorithm there is.

Linear search example, step by step

Let’s look for the number 67 in this 10-position array. It’s out of order on purpose:

Position0123456789
Value523801225767183140
Unsorted array used in the example.
StepPositionValueIs it 67?
1052no: move on to the next one
213no: move on to the next one
3280no: move on to the next one
4312no: move on to the next one
5425no: move on to the next one
657no: move on to the next one
7667yes: found it at position 6
Linear search for the number 67, step by step.
Diagram of linear search for 67 in an unsorted ten-position array: positions 0 to 5 are checked one by one, 67 is found at position 6 after seven comparisons, and positions 7 to 9 are never checked
The search for 67: seven comparisons, one for each position checked.

That took seven comparisons, and positions 7, 8 and 9 didn’t even need to be checked. As soon as the value shows up, the search stops.

See the linear search animation, step by step
Animation of linear search looking for 67 in a ten-position array, comparing one element at a time until it finds it at position 6
The same example in motion: the arrow moves one position at a time, and the positions already checked stay marked.

Linear search in Python, PHP, C and JavaScript

The program below does the same thing in all four languages: it looks for four values in the example array and shows the position of each one. When the value isn’t in the array, the function returns -1.

Python:

# Linear search: look for a value by checking the elements one by one

def linear_search(numbers, target):
    for position in range(len(numbers)):
        if numbers[position] == target:
            return position             # found it: return the position and stop
    return -1                           # checked them all and didn't find it

numbers = [52, 3, 80, 12, 25, 7, 67, 18, 31, 40]

print("position of 67:", linear_search(numbers, 67))
print("position of 52:", linear_search(numbers, 52))
print("position of 40:", linear_search(numbers, 40))
print("position of 5:", linear_search(numbers, 5))

PHP:

<?php
// Linear search: look for a value by checking the elements one by one

function linearSearch(array $numbers, int $target): int
{
    for ($position = 0; $position < count($numbers); $position++) {
        if ($numbers[$position] === $target) {
            return $position;           // found it: return the position and stop
        }
    }
    return -1;                          // checked them all and didn't find it
}

$numbers = [52, 3, 80, 12, 25, 7, 67, 18, 31, 40];

echo "position of 67: ", linearSearch($numbers, 67), "\n";
echo "position of 52: ", linearSearch($numbers, 52), "\n";
echo "position of 40: ", linearSearch($numbers, 40), "\n";
echo "position of 5: ", linearSearch($numbers, 5), "\n";

C:

/* Linear search: look for a value by checking the elements one by one */
#include <stdio.h>

int linear_search(int numbers[], int size, int target) {
    for (int position = 0; position < size; position++) {
        if (numbers[position] == target) {
            return position;            /* found it: return the position and stop */
        }
    }
    return -1;                          /* checked them all and didn't find it */
}

int main(void) {
    int numbers[] = {52, 3, 80, 12, 25, 7, 67, 18, 31, 40};
    int size = 10;

    printf("position of 67: %d\n", linear_search(numbers, size, 67));
    printf("position of 52: %d\n", linear_search(numbers, size, 52));
    printf("position of 40: %d\n", linear_search(numbers, size, 40));
    printf("position of 5: %d\n", linear_search(numbers, size, 5));
    return 0;
}

JavaScript:

// Linear search: look for a value by checking the elements one by one

function linearSearch(numbers, target) {
  for (let position = 0; position < numbers.length; position++) {
    if (numbers[position] === target) {
      return position; // found it: return the position and stop
    }
  }
  return -1; // checked them all and didn't find it
}

const numbers = [52, 3, 80, 12, 25, 7, 67, 18, 31, 40];

console.log("position of 67:", linearSearch(numbers, 67));
console.log("position of 52:", linearSearch(numbers, 52));
console.log("position of 40:", linearSearch(numbers, 40));
console.log("position of 5:", linearSearch(numbers, 5));

Output:

position of 67: 6
position of 52: 0
position of 40: 9
position of 5: -1

The output is the same. A for loop goes through the positions, and an if compares each element with the value you’re looking for. The return inside the loop is what makes the search stop the moment it finds the value. The -1 at the end is only reached when the loop has checked every element and found nothing. Why -1? Because no array position is negative, so there’s no way to confuse it with a real answer.

Focus on the concept, not the language! In all four, the idea is the same: check one by one and stop when you find it.

How many comparisons does linear search make?

It depends on where the value is. That’s why people talk about three cases:

  • Best case: the value is in the first position. One comparison and you’re done.
  • Worst case: the value is in the last position or isn’t in the array. The search checks every element.
  • Average case: if the value can be in any position, with the same chance, the search checks a little more than half of the array on average.

This program counts the comparisons in the example array:

# How many comparisons does linear search make?

def comparisons(numbers, target):
    made = 0
    for value in numbers:
        made = made + 1                 # one comparison for each element checked
        if value == target:
            break
    return made

numbers = [52, 3, 80, 12, 25, 7, 67, 18, 31, 40]

print("52, the first one:", comparisons(numbers, 52))
print("67, partway through:", comparisons(numbers, 67))
print("40, the last one:", comparisons(numbers, 40))
print("5, which isn't in the array:", comparisons(numbers, 5))

total = 0
for value in numbers:
    total = total + comparisons(numbers, value)
print("average, searching for each of the 10 values:", total / len(numbers))

Output:

52, the first one: 1
67, partway through: 7
40, the last one: 10
5, which isn't in the array: 10
average, searching for each of the 10 values: 5.5
Chart of the three cases of linear search in an array with 10 values: 1 comparison in the best case, 5.5 in the average case and 10 in the worst case
The three cases in the 10-value array: 1 comparison in the best case, 5.5 on average and 10 in the worst.

Now you ask: what is this n?

Easy! n is a letter that stands in for a number. Here, that number is how many values the array has, which algorithm analysis calls the input size. In the example array, n = 10. In a list with 500 names, n = 500.

And why not just write the number? Because the count has to work for any array, not only for the one in the example. Without the letter, you’d have to say: in the 10-value array the worst case makes 10 comparisons, in the 500-value one it makes 500, in the 1,000-value one it makes 1,000... and the list would never end. With the letter, one sentence does it: in an array of n values, the worst case makes n comparisons.

This idea comes from algebra, the same one behind the x in the equations you saw at school. In 1591, the French mathematician François Viète published a book in which letters stood for numbers, both the unknown ones and the known ones: vowels for some, consonants for the others. In 1637, René Descartes adopted the first letters of the alphabet (a, b, c) for known values and the last ones (x, y, z) for unknown ones. That’s the convention still used today.

n is one more of those letters. The difference is in what it represents: x is usually a value to be found, while n is a quantity you know when you run the program, but that changes from one array to another. It could be another letter. n is the custom: it’s the one that shows up in the algorithm analysis courses listed in this article’s sources.

One detail: since n counts elements, it’s always a whole number. There are arrays with 3 values and arrays with 4, but not with 3.5.

Got it? Wherever you see n, read “the number of values in the array”. With that, the counts for linear search fit on one line:

For an array with n elements, the best case makes 1 comparison, the worst case makes n and the average case makes (n + 1) ÷ 2. In the 10-value array, the average is (10 + 1) ÷ 2 = 5.5, exactly what the program showed.

Array size (n)Best caseAverage caseWorst case
1015.510
1,0001500.51,000
1,000,0001500,000.51,000,000
Linear search comparisons as the array grows.

What measures are used to explain Big O?

The number of comparisons grows along with the size of the array: double the array and you double the work in the worst case. That’s why linear search is said to have O(n) complexity. To get here, you’ve already used the measures that algorithm analysis works with. Here’s the summary:

MeasureWhat it isIn linear search
Input size (n)The amount of data the algorithm receivesThe n values in the array
Operation countedThe relevant operation, the one that repeatsComparing a value with the target
Best caseThe input that takes the least work1 comparison
Average caseThe average work, with every position equally likely(n + 1) ÷ 2 comparisons
Worst caseThe input that takes the most workn comparisons
Order of growthHow the count grows as n growsLinear: O(n)
The measures of algorithm analysis applied to linear search.

Notice what was left out: time in seconds. It depends on the computer and the compiler, and the idea is to compare algorithms without depending on the machine. That’s why you count how many times the relevant operation runs, and that count is written as a function of n.

Big O notation keeps only the order of growth: it gives an upper bound for the count and ignores the constants that add or multiply. The average case, (n + 1) ÷ 2, is half of n plus a half. Take away the constants and you’re left with n. So the average case and the worst case of linear search are both O(n). The best case, on the other hand, makes 1 comparison for any n: it’s O(1), the cost that doesn’t depend on the input size.

IMPORTANT: when someone just says “this algorithm is O(n)”, they’re usually talking about the worst case, which is the main measure in the analysis.

I’ll say it again because it matters: Big O doesn’t say how many seconds the program takes. It says how the work grows as n grows. If this notation is still new to you, see the article on Big O notation.

Now you ask: is there a search faster than linear search?

There is! It’s binary search, the subject of the next article. It makes at most 20 comparisons in an array of a million values, against a million for linear search in the worst case. But it charges a price: the array has to be sorted.

In the next article, I run a test with this same unsorted array: binary search looks for 52 and answers -1, as if it weren’t there. Linear search, as you saw in the program’s output, found 52 at position 0, right on the first comparison.

That’s why linear search is the right choice in three situations:

  • The array isn’t sorted. Binary search doesn’t work; linear search does.
  • The array is small. With few values, the difference between the two barely shows.
  • There’s only one search. Sorting the array has a cost too, bigger than the cost of one linear search. It isn’t worth sorting everything to search just once.

I’ll say it again because it matters: binary search requires the array to be sorted, and linear search doesn’t require anything. Got it?

Do I have to write linear search every time?

Day to day, no. Languages already come with ready-made functions to look for a value in a list, each with its own names:

LanguageTo know if the value existsTo know the positionWhen it isn’t found
Pythonvalue in listlist.index(value)ValueError error
PHPin_arrayarray_searchfalse
JavaScriptincludesindexOf-1
The ready-made functions of three languages, tested with the example array.

I tested all three with the example array. For 67, all of them answered that it exists and that it’s at position 6. For 5, which isn’t in the array, each one answered in its own way: Python’s index stopped the program with an error, PHP’s array_search returned false and JavaScript’s indexOf returned -1. This was Python’s error:

ValueError: 5 is not in list

IMPORTANT: in PHP, array_search returns the position, and the position can be 0. I looked for 52, which is at position 0, and tested the result with a plain if. PHP treated the 0 as false and answered “not found”, with 52 right at the front! The PHP manual warns about this and tells you to test the return value with the === operator. With if ($position !== false), the answer was the right one: found at position 0.

Another caution: PHP’s in_array uses loose comparison unless you ask for strict comparison. In my test, in_array("67", $numbers) returned true, even with 67 stored as a number and searched for as text. With the third argument set to true, the answer became false. JavaScript was the opposite: indexOf("67") returned -1, because it uses strict equality, the one of ===.

In C, the way to go is the loop written by hand, like in this article’s program.

Even with the ready-made functions, write linear search by hand at least once. Whoever understands how a tool works inside knows when to use it and what to do when it doesn’t fit.

What are the most common mistakes in linear search?

  • Continuing to search after finding it. Without the return (or the break) inside the loop, the program checks the whole array for nothing.
  • Forgetting the case where the value doesn’t exist. Every search needs an answer for “not found”. Here, it’s -1.
  • Confusing position 0 with “not found”. 0 is a valid position. That’s the trap of PHP’s array_search.
  • Getting the last position wrong. In a 10-value array, the last position is 9, not 10.
  • Comparing different types without noticing. The text “67” and the number 67 are equal for PHP’s in_array and different for JavaScript’s indexOf.
  • Using linear search on a huge array that’s already sorted. If the order is already there, binary search does the same job with far fewer comparisons.

Now it’s your turn!

On paper:

  • In the example array, how many comparisons does linear search make to find 25? And to find out that 99 isn’t there?
  • An array has 200 values. How many comparisons does linear search make in the best case, in the worst case and, on average, when the value is in the array?
  • The value you’re looking for appears twice in the array. Which of the two positions does this article’s function return? Why?

On the computer:

  • Change the function to count how many times the value appears in the array, instead of stopping at the first one.
  • Write a function that returns the position of the last occurrence of the value. Hint: you can go through the array from the end to the beginning.
  • Write a linear search that looks for a name in a list of names.

Try it on your own, without asking anyone for the ready-made answer, not even AI!

Linear search doesn’t require anything from the array, but it checks the values one by one. What if the array is already sorted? Then you can throw away half of it with each comparison! In the next article, you’ll meet binary search. See you there!

Stay confident!!!

Sources:

  • Runestone Academy, Problem Solving with Algorithms and Data Structures using Python (Brad Miller and David Ranum). 5.3 The Sequential Search, with 1 comparison in the best case, n in the worst case, about n/2 on average when the item is present, n when it isn’t, and the coefficients that become insignificant as n grows, so the search is O(n).
  • Runestone Academy, Problem Solving with Algorithms and Data Structures using C++. 6.4 The Binary Search, with the warning that, for small values of n, the additional cost of sorting is probably not worth it.
  • Virginia Tech, OpenDSA (Cliff Shaffer). Analyzing Search in Unsorted Lists, with a cost of i + 1 comparisons when the value is at position i and n comparisons when it isn’t in the list.
  • University of Toronto, CSC110/111 course notes (David Liu). 19.2 Average-Case Running Time of Linear Search, with the average case of (n + 1)/2, which is Θ(n).
  • University of California, Irvine, ICS 161 (David Eppstein). Lecture notes: Sequential and Binary Search, with n comparisons in the worst case, when the value is the last one or isn’t in the list, and an average of (n + 1)/2.
  • University at Buffalo, CSE 116. Efficiency of search algorithms, with the best case O(1) on the first element, the worst case O(N) on the last element or a missing one, and the average N/2 that becomes O(N) after dropping the constant.
  • Simon Fraser University, CMPT 125. Linear Search, with n comparisons in the worst case and the worst case as usually more important than the best case.
  • University of California, Berkeley, CS 61B (Jonathan Shewchuk). Lecture 20: Asymptotic Analysis, with the speed of an algorithm expressed independently of the machine, constant factors ignored and Big-Oh as an upper bound.
  • University of British Columbia, CPSC 320 (Jonathan Backer). Big-O Notation and Complexity Analysis, with the count of elementary steps, the worst case as the usual measure and an analysis independent of the machine, the operating system and the compiler (PDF).
  • University of St Andrews, MacTutor. Earliest Uses of Symbols for Variables, with François Viète using vowels and consonants for unknown and known quantities in 1591 and the convention of René Descartes in La Géométrie, from 1637.
  • University of Vermont, CS 1210 (Clayton Cafiero). Finding an element within a list, with the in keyword and the .index() method, which raises a ValueError when the element isn’t in the list.
  • PHP Manual. in_array, with the search that uses loose comparison unless the strict parameter is set.
  • PHP Manual. array_search, with the key of the first element found or false, and the warning to test the return value with the === operator, because 0 also evaluates to false.
  • MDN Web Docs. Array.prototype.indexOf(), with the first index of the element or -1, using strict equality.
  • The examples in this article were run on Python 3.13, PHP 8.3, GCC 13 and Node.js 22.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).