Binary Search
Binary search finds a target in a sorted search space by repeatedly discarding half of the remaining range.
先从这个心智模型开始
Binary search finds a target in a sorted search space by repeatedly discarding half of the remaining range.
它如何工作,不堆砌不必要的术语
Compare target with the middle element.
If target is smaller, continue in the left half; if larger, continue in the right half.
把算法读成一连串决策
Set left and right bounds.
Compute mid without leaving the range.
Move exactly one bound after each comparison until found or left > right.
Searching 23 in [3, 8, 12, 23, 31, 44] checks the middle, then keeps only the half where 23 can still exist.
function binarySearch(items, target) {
let left = 0;
let right = items.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (items[mid] === target) return mid;
if (items[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}不要死记语法。跟踪每一行中发生变化的状态,并把它与上面描述的不变量联系起来。
O(log n)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
适用场景
- Match the algorithm to the structure and preprocessing state of the data.
通常哪里会出错
- Using it on unsorted data.
- Off-by-one errors and infinite loops.
- Not defining whether boundaries are inclusive or half-open.
专业回答结构
Say the invariant: if the target exists, it is inside the current search interval. Then explain how each comparison preserves that invariant while halving the interval.
What problem does Binary Search solve?
Binary search finds a target in a sorted search space by repeatedly discarding half of the remaining range.
关于复杂度应该提到什么?
Its typical cost here is O(log n), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
最常见的错误是什么?
Using it on unsorted data.