Binary Search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one. 二分搜索是一种在有序列表查找项目的算法。 它的原理是不断将可能包含目标值的列表部分一分为二(/2), 直到找到目标值或确定目标值不存在。
If the array is unsorted, looking at the middle element gives us NO information about whether the target is to the left or right. 如果数组只是乱序的,切中间无法判断在左边还是右边。
This is the simplest search algorithm. It's often used as the "baseline" comparison ("The Bad Example" for large data). Unlike Binary Search, it does not require the array to be sorted. 这是最简单、最基础的搜索算法,也是我们用来做对比的"反面教材"(在数据量大时)。 它不需要数组是排好序的。
It's like looking for a book on a messy shelf. You have to pick up the first book, check it, then the second, and so on. If the book is at the end (or not there), you check every single one. 就像在一个乱序的书架上找书。 你只能从第一本开始,拿起来看看是不是,不是就看下一本,直到找到为止。
| Feature特性 | Linear Search线性搜索 | Binary Search二分搜索 |
|---|---|---|
| Pre-condition 前提条件 | None (Unsorted OK) 无 (乱序也行) | Must be Sorted 必须有序 |
| Speed 速度 | Slow O(n) 慢 O(n) | Fast O(log n) 快 O(log n) |
| Implementation 实现难度 | Simple 极简 | Tricky (Boundaries) 稍难 (边界处理) |
| Scenario 适用场景 | Small / Unsorted Data 数据少、无序数组 | Large / Sorted Data 数据多、已排序数组 |
Question: How much longer does an n² algorithm take if input is 5x larger? 问题:如果有两个循环嵌套(n² 的复杂度),数据量变成了原来的 5倍,时间会变成多少倍?
Answer: 25 times slower. (5 * 5 = 25) 答案:时间会变慢 25倍。(5 * 5 = 25)
Example: If 10 items take 100s, 50 items will take 2500s. 原理解释:比如本来处理 10 个数据要 100 秒,现在处理 50 个数据(5倍),就要 2500 秒。
Question: How much longer does an n³ algorithm take if input is 3x larger? 问题:如果有三个循环嵌套(n³ 的复杂度),数据量变成了原来的 3倍,时间会变成多少倍?
Answer: 27 times slower. (3 * 3 * 3 = 27) 答案:时间会变慢 27倍。(3 * 3 * 3 = 27)
Explanation: Cubic growth is explosive. A small increase in data causes a massive increase in time. 原理解释:三次方增长是非常恐怖的,数据稍微多一点点,时间就指数级爆炸。
Example 3: 6n log(n) + 5n + 2 例子 3:6n log(n) + 5n + 2
Example 4: 2n² + 4n + log(n) 例子 4:2n² + 4n + log(n)
We care about trends, not details.
If Elon Musk (Net worth $200B) picks up $100, he is still in the "Billionaire" tier.
Similarly, O(n) + 100 is still just O(n). The constant doesn't change the scale.
因为我们在乎的是 趋势,而不是细节。
这就好比比富:马斯克(身价 2000 亿)在地上捡了 100 块钱,这根本不影响他和普通人之间的数量级差距。
The algorithm maintains a low and high index.
In each step, calculate mid and compare with target.
算法维护 low 和 high 索引。
每一步计算 mid 并与目标值比较。