Given an array of a million sorted values, how many comparisons would a linear search and a binary search each need?
A linear search needs up to a million comparisons in the worst case, and half a million on average if the target is uniformly distributed. A binary search needs at most twenty, because each comparison halves the remaining interval.
import math
for n in (1000, 1000000):
linear = n
binary = math.ceil(math.log2(n + 1))
print(n, linear, binary)The output shows a thousand values needing a thousand comparisons against ten, and a million values needing a million comparisons against twenty. The logarithm is doing all the work: solving two to the power k greater than or equal to n gives k, so the number of probes is the ceiling of the base two logarithm of one more than the size.
This is the question interviewers use to see whether you can connect an asymptotic bound to a concrete number. Saying binary search is O of log n is the easy half. The stronger answer adds the arithmetic, because the interviewer is really asking whether you can size a system: at twenty comparisons per lookup and a million lookups per second, that is twenty million comparisons per second, which is comfortable on any modern core. The linear version at a million comparisons per lookup is not.
The trade-off to state is that binary search requires sorted data, and sorting a million elements costs about twenty million comparisons with a comparison sort. So for a single lookup, scanning is cheaper overall. The logarithmic search only pays for itself when you will query the same collection repeatedly, which is exactly the situation where keeping an index is the right design.