2 / 7 · Basic
Searching: linear and binary search
To find one name in a sorted list of a million, binary search never needs more than 20 checks.
Jump to the 11 practice questionsYou will learn
- Search a list one value at a time
- Count the checks each method needs
Before this: What an algorithm is
1Explain
Looking for one value
Searching is the problem of finding where a value is in a collection, or learning that it is not there. Your phone does it when you type a contact's name, a shop does it when it checks whether an item is in stock, and a spell checker does it for every word you type. The input is a list and a target value. The output is the position of the target, or a sign such as -1 meaning "not found".
2Explore
Linear search
The plainest method is to start at the left and check each value in turn until you find the target or run out of list. This is linear search. It works on any list, sorted or not. Its cost depends on luck: if the target is first, one check is enough; if it is last or missing, you check every value. For a list of n values the worst case is n checks.
Look for 23 from the left. Each step checks one bar; the counter shows how many checks so far.
3Problem
Checks to find 23
In the same list, how many checks does linear search make to find 23?
Hint
23 is at position 5, counting from 0.
Solution
Answer: 6
Linear search checks from the front without skipping any value. 23 is at position 5 counting from 0, so the sixth check finds it.
4Problem
The worst case
At most how many checks does linear search need for a list of 1,000 values?
Hint
The target is last, or not there at all.
Solution
Answer: 1000
In the worst case (target last or missing) it checks every value.
5Explore
Binary search
If the list is sorted, you can do much better. Think of the number guessing game: someone picks a number from 1 to 100 and answers only "higher" or "lower". A sensible player guesses 50 first. Whatever the answer, half the possibilities are gone. The next guess is the middle of what is left, and so on. Binary search does exactly this with a sorted list.
lo and hi mark the part that is still possible; faded bars are already ruled out. mid is checked each step.
6Problem
Checks for 23, binary
In the list [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], how many checks does binary search make to find 23?
Hint
Middle values checked: 16, then 56, then 23.
Solution
Answer: 3
Each check compares the target with the middle value and discards one side. mid = 4 (16 < 23), then mid = 7 (56 > 23), then mid = 5 (23). Three checks.
7Problem
The middle is 40, the target 25
Binary search checks a middle value 40 while looking for 25. What happens next?
Hint
25 is smaller than 40. Which side can it be on?
Solution
Answer: hi moves to just before the middle
40 > 25, so the target can only be to the left of the middle.
8Explore
When the value is missing
Look for 7. After three checks lo passes hi, nothing is left, and the answer is -1.
9Explain
How many checks?
Each check of binary search at least halves the part that is left. Starting from n values, after one check at most about n/2 remain, after two about n/4, and so on until one value is left. The number of halvings needed to get from n down to 1 is the base 2 logarithm of n, written log₂ n. Counting the final check as well, binary search needs at most ⌊log₂ n⌋ + 1 checks, where ⌊ ⌋ means rounding down.
| List size n | Linear search, worst case | Binary search, worst case |
|---|---|---|
| 7 | 7 | 3 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
| 1,000,000,000 | 1,000,000,000 | 30 |
10Problem
1,000 values
At most how many checks does binary search need for a sorted list of 1,000 values?
Hint
2⁹ = 512 and 2¹⁰ = 1,024.
Solution
Answer: 10
Each check halves the range, so 1,000 values need ⌊log₂ 1000⌋ + 1 = 9 + 1 = 10 checks, since 2⁹ = 512 ≤ 1000 < 1024 = 2¹⁰.
11Problem
Twice as long
A list doubles in size. What happens to the worst-case number of binary search checks?
Hint
One more check halves the doubled list back.
Solution
Answer: It grows by about one
One extra check halves the doubled list back to the old size.
12Problem
The guessing game
You may guess a number from 1 to 100 and are told "higher" or "lower". With the best strategy, how many guesses are always enough?
Hint
2⁶ = 64 is less than 100, 2⁷ = 128 is not.
Solution
Answer: 7
⌊log₂ 100⌋ + 1 = 6 + 1 = 7. Six guesses are not always enough because 2⁶ − 1 = 63 < 100.
13Explain
The catch: the list must be sorted
Binary search only works because, in a sorted list, one comparison tells you which side the target must be on. On an unsorted list the middle value tells you nothing about its neighbours, so you are back to linear search. Sorting takes work of its own (the next two units are about that), so the choice depends on use. If you search a list once, a linear search may be cheapest. If you search the same list thousands of times, sorting it once and then using binary search pays off quickly.
14Problem
One search, unsorted list
You will look up a single value in an unsorted list once. Which is cheaper?
Hint
Sorting alone already looks at every value more than once.
Solution
Answer: Linear search
Sorting alone costs more than one linear pass, so it only pays off when you search many times.
15Practice
Write linear search
Write linearSearch so it prints 4 (the position of 23, counting from 0) and then -1.
4
-1const list = [4, 8, 15, 16, 23, 42];
function linearSearch(list, target) {
// Return the index of target, or -1.
}
console.log(linearSearch(list, 23));
console.log(linearSearch(list, 99));
Hint
return -1 goes after the loop, once every value has been checked.
A solution
const list = [4, 8, 15, 16, 23, 42];
function linearSearch(list, target) {
for (let i = 0; i < list.length; i++) {
if (list[i] === target) return i;
}
return -1;
}
console.log(linearSearch(list, 23));
console.log(linearSearch(list, 99));16Practice
Finish binary search
Fill in the loop of binarySearch and delete the break line. It should print 5 and then -1.
5
-1const list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
function binarySearch(list, target) {
let lo = 0, hi = list.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
// If list[mid] is the target, return mid.
// If list[mid] < target, move lo; otherwise move hi.
break; // delete this line when the loop is done
}
return -1;
}
console.log(binarySearch(list, 23));
console.log(binarySearch(list, 7));
Hint
If the middle value is smaller than the target, the target is to the right: move lo.
A solution
const list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
function binarySearch(list, target) {
let lo = 0, hi = list.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (list[mid] === target) return mid;
if (list[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
console.log(binarySearch(list, 23));
console.log(binarySearch(list, 7));17Problem
lo = mid
Why can lo = mid (instead of mid + 1) make binary search loop forever?
Hint
Try lo = 4 and hi = 5.
Solution
Answer: With two values left, mid can stay the same every round
If lo = 4 and hi = 5, mid = 4 and lo = mid leaves lo at 4, so the range never shrinks.
18Explain
Common mistakes
const list = [2, 5, 8, 12, 16];
let lo = 0, hi = list.length;
const target = 99;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (list[mid] < target) lo = mid + 1;
else hi = mid - 1;
console.log("checked", mid, list[mid]);
}checked 2 8
checked 4 16
checked 5 undefinedconst list = [2, 5, 8, 12, 16];
let lo = 0, hi = list.length - 1;
const target = 99;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (list[mid] < target) lo = mid + 1;
else hi = mid - 1;
console.log("checked", mid, list[mid]);
}checked 2 8
checked 3 12
checked 4 16hi starts at the last index, length - 1. Starting at length reads one place past the end, where JavaScript gives undefined.
const list = [91, 2, 56, 23, 8];
function binarySearch(list, target) {
let lo = 0, hi = list.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (list[mid] === target) return mid;
if (list[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
console.log(binarySearch(list, 23));-1const list = [91, 2, 56, 23, 8].sort((x, y) => x - y);
function binarySearch(list, target) {
let lo = 0, hi = list.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (list[mid] === target) return mid;
if (list[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
console.log(binarySearch(list, 23));2On an unsorted list binary search can miss a value that is there. Sort first (with a number comparison), then search.
19
Summary
- Linear search checks one value at a time: up to n checks.
- Binary search halves the range that is left: up to ⌊log₂ n⌋ + 1 checks.
- Binary search only works on a sorted list.
- A million values: 20 checks at most.
- Update with mid + 1 and mid − 1 so the range always shrinks.