Binary Search
Consider a list of 1 million sorted values. Linear search starts at the beginning of the list and asks, “Is this value what I’m looking for?” If it isn’t, the same is asked about the second value, and then the third. Up to 1 million questions are asked. This algorithm doesn’t take advantage of the list being sorted.
Here’s a new algorithm, called binary search, that relies on the list being sorted: look at the middle value and ask, “Is this value bigger than or smaller than the one I’m looking for?” With that one question, we can eliminate 500,000 values! That leaves a list of 500,000 values to search. We’ll do it again: look at the middle value, ask the same question, and eliminate another 250,000 values. We have eliminated ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access