Computer science
Searching
How does a computer find an entry in huge lists in a flash?
What you need first
You search all the time: a name in your chat history, a song in your playlist, a word in the dictionary. Computers search constantly too, just in much bigger lists. Let's look at how they do it cleverly.
Linear search: one by one
The simplest idea: you go through the list from front to back and check every entry until you find the right one. That's called linear search. It always works, even if the list is a mess. But it can take a while: if the entry you want is at the very end of a list with 1000 entries, you need 1000 steps.
Binary search: always halve
If the list is sorted, it gets much faster. Think of a phone book: you're looking for 'Meier' and open it in the middle. If you see 'Schulz' there, you know right away that 'Meier' is in the front half. You can throw away the back half completely. Then you halve the front half again, and so on. That's binary search: every step cuts the list in half.
Linear search: 11 steps
Binary search: 4 steps
Counting steps
A step here always means: you look at one entry and compare it with the one you want. The difference between the two methods is huge. With 1000 entries, linear search needs up to 1000 steps in the worst case. Binary search halves: 1000, 500, 250, 125 and so on. After about 10 halvings only one entry is left. 10 steps instead of 1000! The bigger the list, the more clearly halving wins.
The requirement: sorted
Binary search has a catch: it only works if the list is sorted. Only then does the look at the middle tell you which half to keep searching in. In an unsorted list, linear search is your only option. That's why sorting is so important, and that's exactly what the next topic is about.
Exercises
0 of 6 solvedTime to try it yourself. You can't break anything, every attempt counts.
Where does linear search start in a list?
A list has 10 entries and the name you want is in the last position. How many entries does linear search check?
In an unsorted list, the number you want sits in the fourth position from the front. How many entries does linear search compare until it finds the number?
Match the terms with their descriptions.
What must be true for binary search to work?
Put the steps of binary search in the correct order.
- 1Repeat with the remaining half
- 2Check whether the list is sorted
- 3Look at the middle of the list
- 4Throw away the half that cannot contain the entry you want
Where this leads