Algorithmic Efficiency
引入
9:10
算法与编程
想象一本有一百万个名字的电话簿,你必须找到其中一个。逐个检查,你可能一整天都找不完。有一种方法可以在大约…内找到它
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| Algorithmic efficiency/ˌælɡəˈrɪθmɪk ɪˈfɪʃənsi/ | 算法效率 | suàn fǎ xiào lǜ |
| slow/sləʊ/ | 缓慢 | huǎn màn |
| steps/steps/ | 步骤 | bù zhòu |
| reasonable/ˈriːzənəbl/ | 合理 | hé lǐ |
| unreasonable/ʌnˈriːzənəbl/ | 不合理 | bù hé lǐ |
| heuristic/hjuːˈrɪstɪk/ | 启发式方法 | qǐ fā shì fāng fǎ |
正确未必够好
- 两个算法能都正确,但一个可能好用得多。
- 算法效率(algorithmic efficiency)按算法使用的资源比较它们——主要是时间和内存。
- 一个正确但慢的算法在大输入上可能没用。
- 所以我们需要一种方式来比较它们如何扩展。
Algorithmic efficiency compares algorithms by:
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Efficiency is about time and memory as input grows.
随 n 增长计步
- 估计一个算法随其输入大小 $n$ 增长所用的步骤(steps)数。
- 线性搜索约用 $n$ 步;二分搜索约 $\log_2 n$;比较每一对约 $n^2$。
- 随着 $n$ 变大,这些差异变得巨大。
- 增长的形状远比秒表重要。

算法运行时间随输入规模 n 增长的方式
How running time grows with n
Slide n and compare the curves: log n stays almost flat, n rises steadily, n² explodes. This is why we compare algorithms by how they scale, not with a stopwatch.
Match each algorithm to its rough number of steps for input size n.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
These growth rates decide which algorithm scales.
Which growth is considered unreasonable as n gets large?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Exponential growth quickly becomes far too slow.
When an exact answer is too slow, a ______ finds a good-enough solution fast.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
A heuristic trades a perfect answer for speed.
合理与不合理
- 我们区分合理(reasonable)的运行时间和不合理(unreasonable)的。
- 大致来说,像 $n$ 或 $n^2$ 的增长是合理的;每多一项就翻倍步骤(像 $2^n$)则不是。
- 当精确答案太慢,用一个启发式方法(heuristic)——快速找到的一个足够好的解。
- 不完美,但当完美在时间上不可能时有用。
A binary search of 1,000,000 sorted items needs at most about how many steps? (2^20 ≈ a million)
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Because 2^20 is just over a million, ~20 halvings suffice.
If an algorithm is correct, it will always run fast enough on large inputs.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
False. A correct algorithm can still be too slow on large inputs; it must also finish in a reasonable time.
慢到无法使用
- 这就是为什么有些正确的算法在处理大输入时缓慢得无法实际运行。
- 正确还不够——算法还必须在合理的时间内完成。
**一百万项。**对 1,000,000 个已排序的项进行线性搜索,最多可能需要 1,000,000 步。二分搜索最多只需要约 20 步,因为 $2^{20}$ 略大于一百万。对于较短的列表,差距几乎无关紧要;对于一百万个已排序的项,二分搜索可以大幅减少比较次数。

算法效率随输入大小 $n$ 增长按资源比较算法:线性 $n$、二分 $\log_2 n$、每一对 $n^2$。像 $n$ 或 $n^2$ 的增长是合理的;$2^n$ 是不合理的(用一个启发式方法)。一个在大输入上太缓慢的正确算法不够好。
出了什么问题?只有网站团队能看到这些信息。