Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.11 (1 of 4): Linear and binary search

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

50 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Guess my number

I think of a number from 1 to 100. You guess. I only say "higher" or "lower".

Would you guess 1, then 2, then 3? No. You would guess 50. If I say "higher", you would guess 75. Each guess throws away about half of the numbers that are left. Computers search this way too.

Key words

WordWhat it meansExample
AlgorithmA set of steps to solve a problem.
Linear searchLook at each item in turn, from the start, until you find it.
Binary searchLook at the middle item and throw away the half that cannot hold the target. Repeat.
TargetThe value you are looking for.
SortedIn order, such as smallest to largest or A to Z.
IndexThe position of an item in a list. The first is 0.
ComparisonChecking one value against another.is it equal to the target?
Best caseThe situation where the algorithm does the least work.
Worst caseThe situation where the algorithm does the most work.

The cells students fill in are left blank in this preview.

Linear search: one by one

In a linear search you start at the first item. Is it the target? If not, go to the next. Keep going until you find it or reach the end.

It is simple. It works on any list, sorted or not.

Try it: linear search

Code: python
names = ["Mei", "Tom", "Aisha", "Sam", "Zara"]
target = "Sam"
position = 0
checks = 0
found_at = -1

while position < len(names) and found_at == -1:
    checks = checks + 1
    if names[position] == target:
        found_at = position
    position = position + 1

print("Found at index", found_at, "after", checks, "checks")

# Try the target "Mei" and then "Bob". How many checks each time?

Make a free account to save your work and track your progress.

Trace table: linear search for Sam

CheckIndexItemIs it Sam?
10MeiNo
21TomNo
32AishaNo
43SamYes: found at index 3

The cells students fill in are left blank in this preview.

Quick check: linear search

Have a go

Quick check: linear search

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Binary search: halve the list

Binary search needs a sorted list. Look at the middle item. Is it the target? Then stop.

If the target is smaller, the answer can only be in the lower half. Throw away the upper half. If the target is larger, do the opposite. Repeat with what is left.

Worked example: binary search, found

StepSearch area (index)MiddleItem in the middleDecision
10 to 631515 is smaller than 27: use the upper part, 4 to 6
24 to 6527It is 27: found at index 5

The cells students fill in are left blank in this preview.

Try it: binary search

Code: python
numbers = [3, 8, 12, 15, 21, 27, 40]
target = 27
low = 0
high = len(numbers) - 1
checks = 0
found_at = -1

while low <= high and found_at == -1:
    middle = (low + high) // 2
    checks = checks + 1
    if numbers[middle] == target:
        found_at = middle
    elif numbers[middle] < target:
        low = middle + 1
    else:
        high = middle - 1

print("Found at index", found_at, "after", checks, "checks")
# // divides and drops the decimal part. Try the target 10.

Make a free account to save your work and track your progress.

Worked example: binary search, not found

StepSearch area (index)MiddleItem in the middleDecision
10 to 631515 is bigger than 10: use the lower part, 0 to 2
20 to 2188 is smaller than 10: use 2 to 2
32 to 221212 is bigger than 10: nothing is left. Not found

The cells students fill in are left blank in this preview.

Put binary search in order

Have a go

Put binary search in order

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Match the word to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Worked example: how many checks?

Items in the listLinear search, worst caseBinary search, worst case
773
1001007
1000100010
1 000 0001 000 00020

The cells students fill in are left blank in this preview.

Which one should you choose?

Binary search is much faster on a big list. But the list must be sorted, and sorting takes time.

Use linear search for a short list, a list that is not sorted, or a search you do only once. Use binary search for a big sorted list that you search again and again, such as every product code in a big shop.

Benefits and drawbacks

BenefitsDrawbacks
Linear searchSimple to write. Works on any list, sorted or not. Fast enough for a short listSlow on a big list: it may check every item
Binary searchVery fast on a big list: it throws away half the list at each stepThe list must be sorted first. Sorting takes time. The code is harder to write

The cells students fill in are left blank in this preview.

Quick check: which search?

Have a go

Quick check: which search?

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Watch: two searches

Press Play on the short film below. It runs both searches on the lists from this lesson. Count the checks each search makes, and watch what goes wrong when the list is not sorted.

Film: linear and binary search

Linear and binary search

Every scene, as text

  1. Linear search looks at each item in turn, from the start, so it works on a list in any order. names is set to Mei, Tom, Aisha, Sam and Zara, in no order, and target is set to "Sam". The first check, at index 0, is Mei: not Sam (an X over it). Then Tom and Aisha: not Sam either. The fourth check, at index 3, is Sam (a tick over it): found at index 3 after 4 checks, the arrow under the item being checked and checks counting up to 4. Zara is never looked at.
  2. Binary search needs a sorted list. numbers is set to 3, 8, 12, 15, 21, 27, 40, smallest to largest, and target is set to 27. Check 1: low is 0 and high is 6, so the middle is index 3, which holds 15. 15 is smaller than 27, so the upper part is used, 4 to 6. Check 2: indexes 0 to 3 are thrown away (struck through), low is 4 and high is 6, so the middle is index 5. It is 27 (a tick over it): found at index 5 in 2 checks.
  3. Myth (false): binary search works on any list. Here it runs on the names list, which is not sorted, with target set to "Mei". Check 1: low is 0 and high is 4, so the middle is index 2, Aisha. Aisha comes before Mei in A to Z order, and binary search trusts the list is sorted, so the upper part is used, 3 to 4, and Mei, at index 0, is thrown away with the lower part (struck through). Check 2: low and the middle are index 3, Sam, and high is 4. Sam comes after Mei, so high becomes 2, below low: nothing is left. Binary search says not found, yet Mei is at index 0.
  4. The cure: sort the list first. names.sort() puts the names in order: Aisha, Mei, Sam, Tom, Zara. Check 1: the middle is index 2, Sam. Sam comes after Mei, so the lower part is used, 0 to 1. Check 2: low is 0 and high is 1, so the middle is (0 + 1) // 2 = 0, rounded down: Aisha. Aisha comes before Mei, so only index 1 is left. Check 3: low, middle and high are all index 1: Mei (a tick over it), found at index 1 after 3 checks. For a short list, linear search is fine too, and needs no sorting.
  5. Worst case: how many checks? The lesson's table. Each check of a binary search throws away about half of what is left. 7 items: linear search 7 checks, binary search 3. 100 items: 100 and 7. 1000 items: 1000 and 10. 1 000 000 items: 1 000 000 and 20. On a big sorted list binary search wins; linear search may check every item.

Your turn: two searches

Write two searches.

  1. linear_search(items, target) looks at the items one by one. It gives back the position of the first match, or -1.
  2. binary_search(items, target) works on a sorted list. It looks at the middle item and keeps one half. It gives back the position, or -1.

One test counts how many items binary search reads in a list of 1000. Up to 60 reads is allowed. A linear search would read 1000, so it fails that test. Press Run Tests to check.

Code: python
def linear_search(items, target):
    # Look at the items one by one, from the start.
    # Give back the position (starting at 0) of the first item equal to target.
    # If it is not there, give back -1.
    return None


def binary_search(items, target):
    # items is a SORTED list. Use binary search: look at the middle item,
    # then throw away the half that cannot hold the target. Repeat.
    # Give back the position of the target, or -1 if it is not there.
    # Do not loop through the whole list.
    # The test counts how many items you read by position. 60 reads is allowed.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.