Binary search
In a sorted sequence you can rule out half of the remaining positions by comparing the middle item with your target.
Simple example
Find 8. The middle value 6 is too small. Search the upper part and print position 4, counting from one.
#include <iostream>
int main() {
int values[] = {2, 4, 6, 8, 10};
int low = 0;
int high = 4;
while (low <= high) {
int middle = low + ((high - low) / 2);
if (values[middle] == 8) {
std::cout << middle + 1 << '\n';
break;
}
if (values[middle] < 8) {
low = middle + 1;
} else {
high = middle - 1;
}
}
}
4
Everyday examples
Open a numbered catalogue
You want page 84 in a catalogue. You open at 60. Which pages can you skip?
All pages through 60 come before 84. Look halfway through the remaining pages.
Check a reserved seat
Reserved seat numbers are 3, 7 and 11. Is seat 8 reserved?
Seven is too small and eleven is too large. The remaining search interval is empty.
Find a date in a diary
A diary is ordered by date. Entries are on days 2, 5 and 9. Which single check finds day 5?
The middle date already matches. Stop immediately.
Cost and limits
Binary search uses O(log n) comparisons. The sequence must be sorted by the same rule used in the search.