Binary Search
引入
9:10
算法与编程
想象一本有一百万个名字的电话簿,你必须找到其中一个。逐个检查,你可能一整天都找不完。有一种方法可以在大约…内找到它
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| sorted/ˈsɔːtɪd/ | 已排序 | yǐ pái xù |
| Binary search/ˈbaɪnəri sɜːtʃ/ | 二分查找 | èr fēn chá zhǎo |
| target/ˈtɑːɡɪt/ | 目标 | mù biāo |
| middle/ˈmɪdl/ | 中间 | zhōng jiān |
| halves/hɑːvz/ | 减半 | jiǎn bàn |
| comparison/kəmˈpærɪsn/ | 比较 | bǐ jiào |
| linear search/ˈlɪnɪə sɜːtʃ/ | 线性查找 | xiàn xìng chá zhǎo |
在已排序列表中快速查找
- 二分查找(binary search)是在已排序(sorted)列表中定位一个目标(target)值的快速方法。
- "已排序"意味着值是有序的——比如从小到大。
- 它比检查每一项快得多。
- 但它有一个严格的要求。
二分查找需要已排序的数据。 在未排序的列表上,它可能跳过目标而错过它。总是先排序——或用另一种查找。
Binary search can only be used on data that is:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
On unsorted data it can miss the target.
检查中间,然后减半
- 想法很简单:检查中间(middle)元素。然后:
- 如果中间等于目标,你找到了;
- 如果目标更小,只搜索左半;
- 如果目标更大,只搜索右半。

二分搜索每步将范围减半(列表必须已排序)
Linear vs binary search
binary halves the range each step
Linear search checks every item; binary search halves a sorted list each comparison, so it needs far fewer steps.
If the list is sorted from smallest to largest and the target is larger than the middle element, binary search next looks in the:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
A larger target must be in the right (higher) half.
Each comparison in binary search ______ the remaining part of the list.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Halving each step is why it is so fast.
About how many binary-search checks are needed for a sorted list of 1000 items? (2^10 = 1024)
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Because 2^10 = 1024 ≥ 1000, about 10 halvings suffice.
为什么它这么快
- 每次比较(comparison)都会使列表的剩余部分减半。
- 对 1000 项,线性搜索可能需要多达 1000 次检查。
- 二分查找最多需要约 10 次,因为 $2^{10} = 1024$。
- 列表越大,优势越大。

Binary search finds 14 in [2,5,8,11,14,17,20] in how many comparisons?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Middle 11 → right; middle 17 → left; middle 14 → found: 3 comparisons.
On a large sorted list, linear search needs fewer comparisons in the worst case than binary search.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
False. Binary search halves the list at each step, so it needs far fewer comparisons than checking every item in turn.
对比线性搜索
- 一个线性查找(linear search)一个一个地检查每个元素。
- 二分查找在大的已排序列表上通过每步减半胜过它。
在 [2, 5, 8, 11, 14, 17, 20] 中搜索 14。 中间是 11;14 > 11 → 搜索右半 [14, 17, 20]。中间是 17;14 < 17 → 搜索 [14]。中间是 14——只用 3 次比较找到。线性搜索本会用 5 次。
二分查找通过检查中间并只保留可能含有它的那一半,在已排序列表中找到目标。每次比较****减半范围,所以 1000 项需要约 10 次检查——远少于线性查找的 1000 次。它只在已排序数据上有效。
出了什么问题?只有网站团队能看到这些信息。