Linear search
how it works
The idea in a few sentences and a picture, then one search step by step.
Linear search looks at the numbers of a row one at a time, from the left. Each look asks one question: is this the number wanted? Yes, and it stops, found. No, and it moves to the next. Past the last number, it is not there. The row may be in any order, since the search never uses the order. Its plain name in Sebastian Bourges' books is reading down, a list read from the top (volume one, chapter 1); its formal names are linear search and sequential search.
Looking for 42: 1 look, found at place 1.
Looking for 56: 5 looks, found at place 5.
Looking for 30: 8 looks, not there.
- a look, numbered in turn
- found, ringed
- looked at, not it
- never reached
step 1 of 12
There are 8 numbers in a row, and their order does not matter. Look for 56, one number at a time from the left.
what it remembers to know where it is
- looking for
- 56
- looking at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 12
Look at place 1. It holds 42. Is that 56?
what it remembers to know where it is
- looking for
- 56
- looking at place
- 1
step 3 of 12
No, 42 is not 56. Rule it out and move to the next.
what it remembers to know where it is
- looking for
- 56
- looking at place
- 1
step 4 of 12
Look at place 2. It holds 7. Is that 56?
what it remembers to know where it is
- looking for
- 56
- looking at place
- 2
step 10 of 12
Look at place 5. It holds 56. Is that 56?
what it remembers to know where it is
- looking for
- 56
- looking at place
- 5
step 11 of 12
Yes. 56 is at place 5, so it is found.
what it remembers to know where it is
- looking for
- 56
- looking at place
- 5
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start at the first numberPython line 7
- look at the numberPython line 8
- if it is the number wanted, it is foundPython line 9
- otherwise rule it out and move to the nextPython line 7
- past the last number, it is not in the rowPython line 10
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def linear_search(row, target):
"""Look at each number of the row, from the left, until one is target.
Returns its place, counted from 0 as Python counts places, or None
when target is not in the row. The row may be in any order.
"""
for place, number in enumerate(row): # from the first number on
if number == target: # one look: is this the number wanted?
return place # found, at the first place it stands
return None # past the last number: it is not in the row
how it scales
How the looks grow, from ten numbers to ten million.
The marks across and up go 10, 100, 1,000 and on, equally spaced. Not there climbs one mark up for each mark across: ten times the numbers, ten times the looks. The average climbs about the same, and standing first stays flat at 1 look.
looks, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- it is not theresolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- it is there once, each place as likelysolid where measured by running it; dashed where its formula carries it on to ten million
- the number wanted stands firstsolid where measured by running it; dashed where its formula carries it on to ten million
| looks | time | |
|---|---|---|
| 1,000 | 1,000 | about 1 microsecond |
| 100,000 | 100,000 | about 100 microseconds |
| 10,000,000 | 10,000,000 | about 10 milliseconds |
The looks are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count the looks of linear search yourself, as this page's plot does.
Run it with Python 3.12 or later. For each size n it shuffles 1 to n and
prints the looks when the number wanted stands first, the cheapest; when it
is not in the row, the dearest; and the average when it is there, each
place as likely, worked out by trying every place. That average is exact;
the plot's points average 20 places spread over the row, about 2 per cent
under it. The counts are the same on any computer; only the time differs.
"""
import random
class Counted:
"""A number that counts every look: each time it is compared."""
looks = 0
def __init__(self, value):
self.value = value
def __eq__(self, other):
Counted.looks += 1
return self.value == other.value
def linear_search(row, target):
"""Look at each number of the row, from the left, until one is target.
Returns its place, counted from 0 as Python counts places, or None
when target is not in the row. The row may be in any order.
"""
for place, number in enumerate(row): # from the first number on
if number == target: # one look: is this the number wanted?
return place # found, at the first place it stands
return None # past the last number: it is not in the row
def count(row, target):
"""How many looks linear search makes looking for target in row."""
Counted.looks = 0
linear_search([Counted(x) for x in row], Counted(target))
return Counted.looks
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'first':>6} {'not there':>10} {'average':>9}")
for n in [10, 100, 1000]:
row = list(range(1, n + 1))
random.shuffle(row) # any order will do
every = sum(count(row, number) for number in row) / n
print(f"{n:>6} {count(row, row[0]):>6} {count(row, 0):>10} {every:>9}")
best, worst and average
One search costs from 1 look up to a look at every number, depending on where the number stands.
A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestthe number wanted stands first | averageit is there once, each place as likely | worstit is not there | |
|---|---|---|---|
| looks | 1, the first look finds it | , about half the row | , a look at every number |
| how the looks grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: one extra box, the place reached; the number wanted comes with the input
Extra memory is the room it needs on top of the input itself, while it runs.
Looking for 15: 1 look, found at place 1.
Looking for 33: 5 looks, found at place 5.
Looking for 20: 5 looks, not there.
Looking for 47: 3 looks, found at place 3.
- a look, numbered in turn
- found, ringed
- looked at, not it
- never reached
- not there,
- there on average,
- standing first, 1
| numbers | standing first | there on average | not there |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 1 | 1.5 | 2 |
| 3 | 1 | 2 | 3 |
| 4 | 1 | 2.5 | 4 |
| 5 | 1 | 3 | 5 |
| 10 | 1 | 5.5 | 10 |
| 100 | 1 | 50.5 | 100 |
| 1,000 | 1 | 500.5 | 1,000 |
where the formula comes from
Each count above, worked out in small steps. Every step names the line it uses.
the move: watch the first look
the line:Looking for 27: 1 look, found at place 1.
- a look, numbered in turn
- found, ringed
- never reached
27 stands first, so the first look finds it. Places 2 to 4 are never reached. why it is allowed: The first look is at place 1, and the number there is the one wanted, so the search stops.
the move: count it
the line:why it is allowed: is the looks when the number wanted stands first. By line 1, one, for 4 numbers or 4 million.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2. An equals gives a ceiling and a floor at once; needs the ceiling, and the floor.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, a fixed number of looks, whatever is.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, 1, which is to say none.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: follow the search
the line:Looking for 50: 4 looks, not there.
- a look, numbered in turn
- looked at, not it
50 is not there, so every place is looked at, 4 looks for 4 numbers. why it is allowed: Each look says no and moves on, so the search reaches the end. It never looks at a place twice.
the move: a look a place
the line:why it is allowed: is the looks for a number not there. By line 1, one for each of the places.
guess it, thenthe move: count the ones
the line:why it is allowed: Line 2 has ones. For 4 numbers, 4.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4, 1 times at most.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: price one place
the line:Looking for 9: 1 look, found at place 1.
Looking for 41: 2 looks, found at place 2.
Looking for 26: 3 looks, found at place 3.
Looking for 70: 4 looks, found at place 4.
Looking for 13: 5 looks, found at place 5.
- a look, numbered in turn
- found, ringed
- looked at, not it
- never reached
Each of the 5 numbers looked for in turn. The number at place 3 costs 3 looks. why it is allowed: Here is the place the number stands at, once in the row. The search looks at places 1 to , then stops. With repeats it stops sooner, as section 3 shows.
the move: average over the places
the line:place looks chance looks times its chance 1 1 a fifth 1 fifth 2 2 a fifth 2 fifths 3 3 a fifth 3 fifths 4 4 a fifth 4 fifths 5 5 a fifth 5 fifths in all 15 5 fifths, which is 1 15 fifths, which is 3 The 5 numbers of line 1, each as likely. The chances add up to 1, and the last column to 3, the average. why it is allowed: is the average looks. By line 1 the places cost 1, 2 and on up to looks. Each place has chance 1 over , so their total is shared by .
guess it, thenthe move: add 1 to n
the line:The looks for places 1 to 5 stand as columns of 1 to 5. The same, hung upside down, fill a rectangle 5 wide and 6 tall, 30 squares. Half is 15, the looks in all. where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line:Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15. why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: The box under this line adds 1 to with two staircases, as the picture does for 5. For 5, 5 times 6 over 2 is 15.
guess it, thenthe move: share by n
the line:why it is allowed: Sharing by takes away the that multiplies . For 5, 15 over 5 is 3, the table's average.
guess it, thenthe move: a floor
the line:why it is allowed: In line 4, is more than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, at least half of .
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 4, 1 is at most .
guess it, thenthe move: halve 2n
the line:why it is allowed: over 2 is .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 9 bound by the same growth, . On average, about half the row.
guess it, then
try it on small inputs: over the number at each of 5 places, 15 looks in all, the average is
the move: what one look keeps
the line:The first look, at 35. 66 must be after it, so binary search keeps those 4 and drops the rest. why it is allowed: Binary search needs the row in order. It looks at the middle of what is left and keeps the side the number must be on. The look itself is in neither side, and of two middles it takes the first. So of these 8, the side after holds 4, half rounded down, and the side before 3.
the move: count the halvings
the line:7 lies between 4 and 8, so its log lies between 2 and 3 and rounds down to 2. That is 3 looks for 7 numbers. 8 halved, rounding down, goes 4, 2 and 1. Three halvings, then one more look reads the last number, so 4 looks. why it is allowed: is the most looks. 66 keeps exactly half at each look: 8 numbers, then 4, 2 and 1, three halvings, and a fourth look reads the last. Fewer numbers never cost more looks, as the box under line 3 shows. So the most is the halvings, plus 1.
guess it, thenthe move: use the page on halving
the line:where does this come from?
question 3 of the page halving and logarithmsBinary search on a row of numbers. At most how many looks? the move: what one look keeps
the line:8 numbers have two middles; the table's 7 have one. look still to search half, rounded down the middle kept 1 10, 20, 30, 40, 50, 60, 70 3.5 to 3 40 50, 60, 70 2 50, 60, 70 1.5 to 1 60 70 3 70 0.5 to 0 70 none 75 is above all 7 numbers, so each look keeps the side after. why it is allowed: This site's binary search looks at the middle of what is left, the first of two middles, and keeps the side the wanted number must be on. From 8 it keeps 3 before or 4 after: the side after holds half, rounded down, the side before no more.
the move: fewer numbers, no more looks
the line:after look keeping the bigger side keeping the smaller side 0 10 10 1 5 4 2 2 1 3 1 none 4 none Two searches on 10 numbers. Keeping the bigger side runs out after 4 looks, the smaller after 3. why it is allowed: Let A always keep the bigger side, and S be any search on the same row. While S holds no more than A, it keeps at most half of its part, rounded down, so no more than A keeps. In the table, S keeps 4 to A's 5, then 1 to 2. So S runs out no later.
the move: a number that keeps the bigger side
the line:why it is allowed: Each middle is too small, so each look keeps the side after it. That is A of line 2.
the move: count that search's looks
the line:why it is allowed: Each look halves, rounding down, so question 2 of the page halving and logarithms counts the looks to one number. 1 number takes no halving, log 0. For 7, 7 leaves 3, 3 leaves 1, and look 3 leaves none.
the move: the most looks
the line:why it is allowed: Let be the most looks, which lines 2 to 4 count. For 7 numbers, the search for 75 takes 3, as the table at line 1 shows.
the move: read it
the line:why it is allowed: For 7 numbers, 2 and 1 more. For 16, 4 and 1 more.
why it is allowed: The box under this line works out the most looks as . 8 halves to 4, 2 and 1: three halvings, as 2 times 2 times 2 is 8, so the log of 8 is 3, and 4 looks. 7 goes to 3 and 1: two halvings, 3 looks. 2 to the power 0 is 1, so the log of 1 is 0: 1 look.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
Count every look on the row 64, 15, 38, 9, 71, looking for 40, which is not there.
| step | what happens | looks |
|---|---|---|
| 1 | There are 5 numbers in a row, and their order does not matter. Look for 40, one number at a time from the left. | 0 |
| 2 | Look at place 1. It holds 64. Is that 40? | 1 |
| 3 | No, 64 is not 40. Rule it out and move to the next. | 1 |
| 4 | Look at place 2. It holds 15. Is that 40? | 2 |
| 5 | No, 15 is not 40. Rule it out and move to the next. | 2 |
| 6 | Look at place 3. It holds 38. Is that 40? | 3 |
| 7 | No, 38 is not 40. Rule it out and move to the next. | 3 |
| 8 | Look at place 4. It holds 9. Is that 40? | 4 |
| 9 | No, 9 is not 40. Rule it out and move to the next. | 4 |
| 10 | Look at place 5. It holds 71. Is that 40? | 5 |
| 11 | No, 71 is not 40. Rule it out and move to the next. | 5 |
| 12 | All 5 numbers are ruled out, so 40 is not in the row. | 5 |
| 13 | Done after 5 looks. | 5 |
In all, 5 looks. The formula from section 4, , gives at : the same.
where you meet it
Most programming languages hand you linear search ready made.
Python's in and index
The table below asks Python for 23 and 30 in the row 7, 23, 31, 23, 56, 12, kept as a list, Python's row of items. in and index search it as this page does, from index 0. For 30, index stops with an error, ValueError.
source: the Python tutorial, More on Lists (opens in a new tab), list.index; Common Sequence Operations (opens in a new tab); CPython's Objects/listobject.c, list_index_impl and list_contains
JavaScript's indexOf and includes
An array is JavaScript's row of items. Asked for 30, indexOf searches it the same way and gives minus 1, its word for not there. includes walks it the same way for whole numbers, but answers true or false.
source: the ECMAScript specification, ECMA-262 (opens in a new tab), Array.prototype.indexOf and Array.prototype.includes
a database with no index
A database index is a guide to a column, as a book's index is to its pages. A database with no index on a column reads every record to find a value, which PostgreSQL calls a sequential scan: this page's not there.
source: the PostgreSQL documentation, Using EXPLAIN (opens in a new tab) and Indexes, Introduction (opens in a new tab)
| asked | answer | why |
|---|---|---|
| row.index(23) | 1 | place 2 on this page, the first 23 |
| 23 in row | True | found at the second look |
| row.index(30) | ValueError | every item looked at, none equal |
| linear_search(row, 30) | None | this page's Python, for not there |
| indexOf(30), in JavaScript | minus 1 | its word for not there |
what is used instead
A row kept in order and searched often is searched with binary search instead, each look halving what is left. For many searches, a dictionary finds a key without looking at every one. Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, weigh this in volume one, chapter 1. "On twenty items the difference is about ten looks against four, and simplicity is worth six looks". On 20 numbers this page's average is 21 over 2, which is 10.5. And sorting a row only to search it once does not pay: "you have spent far more than you saved".
how it compares
Linear search beside three searches that need the row in order.
| way | how it looks | needs the row in order | most looks | most on 12 numbers | reach for it when |
|---|---|---|---|---|---|
| linear search | one number at a time, from the left | no | 12 | the row is short, or in no order and searched once | |
| binary search | the middle of what is left, keeping one side | yes | , by the last question of section 4 | 4 | the row is in order and searched many times |
| jump search | a block at a time, then through the block | yes | at most twice the root of the numbers, plus 2, by its own page | 7 | the row is in order but can only be read from the front, as on tape |
| interpolation search | guesses the place from the number's size | yes | one fewer than the numbers from 2 numbers on, by its own page | 1 on 8, 16 and on to 96; 10 on 1 to 11 then 99 | the row is long, in order, and close to equal steps |
- linear search, not there,
- linear search, there on average,
- binary search at most,