What is the time complexity of binary search?
O(log n). Every comparison halves the range, so a list of n items is exhausted after at most ⌊log₂ n⌋ + 1 comparisons: 4 for 15 items, 10 for 1 000, 20 for a million.
The best case is O(1), when the first middle item happens to be the target. The average case is still O(log n), about one comparison fewer than the worst. The loop version needs O(1) extra memory; a recursive version uses O(log n) stack frames.
Why does binary search only work on a sorted array?
Because the whole method rests on one inference: “this item is too small, so everything before it is too small as well.” That is only true when the items are in order. On unsorted data a comparison tells you about one item and nothing about its neighbours, so nothing can be thrown away.
If the data is not sorted and you only search it once, a linear scan (O(n)) is cheaper than sorting first (O(n log n)). Sorting pays off when the same list is searched many times.
What is the difference between binary search and linear search?
A linear search checks items one after another from the start; it works on any list and takes up to n checks. Binary search jumps to the middle and halves the range each time; it needs sorted data and random access, and takes about log₂ n checks.
For a handful of items the two are equally quick, and a linear scan is simpler. The gap opens fast: at a million items it is 20 checks against as many as a million.
Why is mid sometimes written as lo + (hi − lo) / 2?
In languages with fixed-size integers, lo + hi can overflow when both are large, producing a negative index. lo + (hi − lo) / 2 gives the same middle without ever exceeding hi.
This is not a theoretical worry: a bug of exactly this kind sat in the binary search of Java’s standard library for years before it was reported in 2006. Python integers do not overflow, so there (lo + hi) // 2 is fine.
What does binary search return if the value is not found?
The loop ends when lo has moved past hi. The simple version returns −1 (or “not found”). But lo now points at the first item larger than the target, which is exactly where the target would be inserted to keep the list sorted.
Library versions expose that: Python’s bisect_left and C++’s lower_bound return the insertion point instead of a yes or no. The same variants decide what happens with duplicates, by returning the first matching position rather than whichever one the probes land on.
Can you use binary search on a linked list?
Not usefully. Binary search needs to jump to the middle in one step, and a linked list can only be walked node by node, so each “jump” costs O(n) and the advantage is gone.
When data must stay sorted and change often, a balanced search tree or a skip list gives the same halving idea with cheap inserts.