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
| Word | What it means | Example |
|---|---|---|
| Algorithm | A set of steps to solve a problem. | |
| Linear search | Look at each item in turn, from the start, until you find it. | |
| Binary search | Look at the middle item and throw away the half that cannot hold the target. Repeat. | |
| Target | The value you are looking for. | |
| Sorted | In order, such as smallest to largest or A to Z. | |
| Index | The position of an item in a list. The first is 0. | |
| Comparison | Checking one value against another. | is it equal to the target? |
| Best case | The situation where the algorithm does the least work. | |
| Worst case | The 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
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
| Check | Index | Item | Is it Sam? |
|---|---|---|---|
| 1 | 0 | Mei | No |
| 2 | 1 | Tom | No |
| 3 | 2 | Aisha | No |
| 4 | 3 | Sam | Yes: 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 questionsBinary 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
| Step | Search area (index) | Middle | Item in the middle | Decision |
|---|---|---|---|---|
| 1 | 0 to 6 | 3 | 15 | 15 is smaller than 27: use the upper part, 4 to 6 |
| 2 | 4 to 6 | 5 | 27 | It is 27: found at index 5 |
The cells students fill in are left blank in this preview.
Try it: binary search
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
| Step | Search area (index) | Middle | Item in the middle | Decision |
|---|---|---|---|---|
| 1 | 0 to 6 | 3 | 15 | 15 is bigger than 10: use the lower part, 0 to 2 |
| 2 | 0 to 2 | 1 | 8 | 8 is smaller than 10: use 2 to 2 |
| 3 | 2 to 2 | 2 | 12 | 12 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 questionsMatch 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 list | Linear search, worst case | Binary search, worst case |
|---|---|---|
| 7 | 7 | 3 |
| 100 | 100 | 7 |
| 1000 | 1000 | 10 |
| 1 000 000 | 1 000 000 | 20 |
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
| Benefits | Drawbacks | |
|---|---|---|
| Linear search | Simple to write. Works on any list, sorted or not. Fast enough for a short list | Slow on a big list: it may check every item |
| Binary search | Very fast on a big list: it throws away half the list at each step | The 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 questionsWatch: 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
- 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.
- 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.
- 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.
- 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.
- 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.
linear_search(items, target)looks at the items one by one. It gives back the position of the first match, or -1.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.
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