What is a Binary Search and how does it improve search efficiency?
Instruction: Discuss the process of binary search, its algorithmic complexity, and why it is more efficient compared to linear search, especially in certain contexts.
Updated
Official answer
Binary search repeatedly discards half of an ordered search interval. For a sorted random-access sequence, this Python function returns the first position of a target or -1:
def binary_search(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo if lo < len(a) and a[lo] == target else -1
The invariant is that elements before lo are below the target, and elements at or beyond hi are at least the target. The half-open interval shrinks each iteration; empty input and duplicate values are handled without special loops.
There are O(log n) midpoint probes and O(1) auxiliary space, assuming constant-time indexing and comparisons. A million elements need about 20 probes, not necessarily only 20 individual comparison operations. A linked list does not provide constant-time middle access.
The sorted/consistent-order precondition matters. Sorting for one search may cost more than a linear scan; repeated queries can amortize preprocessing. Inserting into a sorted array can still require O(n) movement even though locating the insertion point is logarithmic.
Related Questions
-
easy
-
medium
-
hard
-
hard