Linear search and binary search
Both searches look for the same target in the same sorted list. Press Step to move both forward together, or Play. Linear search checks every box from the left; binary search checks the middle and throws away half each time. Compare the number of checks.
Linear search: 0 checks
Binary search: 0 checks
How the work grows
Linear search
Check each item in turn until you find the target or reach the end. It works on any list, sorted or not. On average it checks half the list, and in the worst case all of it: for n items, up to n checks. Its running time is O(n).
Binary search
Binary search only works on a sorted list. Look at the middle item. If it is the target, stop. If the target is bigger, it must be in the right half, so throw the left half away; if smaller, throw the right half away. Repeat on the half that is left. Each check halves the list, so a million items need at most 20 checks. Its running time is O(log n).
The low, high and mid pointers
Programs keep two positions, low and high, marking the part of the list still in play, and work out mid = (low + high) ÷ 2, rounded down. If the target is bigger than the middle item, low becomes mid + 1; if smaller, high becomes mid − 1. When low passes high, the target is not there.
Which one to use?
For a short list, or one that changes all the time, linear search is simplest. For a big list you search often, sort it once (see the sorting visualiser) and use binary search, or store it in a binary search tree. The guessing game “higher or lower” is binary search: the best first guess between 1 and 100 is 50.
Questions students ask
Why does binary search need a sorted list?
Binary search needs a sorted list because it decides which half to throw away by comparing the target with the middle value; that only works if every value on the left is smaller and every value on the right is bigger.
How many steps does binary search take?
Binary search takes at most about log₂(n) + 1 steps for a list of n items, so 1 000 items need at most 10 checks and 1 000 000 items need at most 20.
Is linear search ever better than binary search?
Linear search is better when the list is unsorted and only searched once, or is very short, because sorting first would take longer than simply checking each item.
Check yourself
3 quick questions. Tap an answer to see if you are right.
1. Binary search only works on a list that is…
It decides which half to discard by comparing with the middle value.
2. At most how many checks does binary search need for 1 000 000 items?
2²⁰ ≈ 1 000 000, so about 20 halvings.
3. Linear search on n items is…
In the worst case it checks every item once.