Searching and Sorting查找与排序
Searching and sorting are the workhorses of computer science: almost every program either looks something up or arranges data in order. This guide builds the two core search algorithms (linear search and binary search), explains why one is dramatically faster on sorted data, introduces algorithm efficiency concepts, then covers the three classic sorts (bubble, selection, insertion) with step-by-step traces and Python code. The final section compares all algorithms and shows how to use Python's built-in sort in practice. Code blocks are in Python/pseudocode throughout; Chinese annotations follow each block.查找(search,查找)与排序(sort,排序)是计算机科学的主力算法:几乎每个程序都需要查找数据或将数据排成顺序。本指南系统讲解两大查找算法(线性查找与二分查找),说明为何二分查找在有序数据上效率显著更高,引入算法效率(algorithm efficiency,算法效率)概念,再逐步演示三种经典排序(冒泡、选择、插入),并附 Python 实现。最后一节比较所有算法并展示如何在实践中使用 Python 内置排序。全部代码使用 Python/伪代码,每段后附中文注解。
Linear Search线性查找
- State the pre-condition (none) and the best and worst case of linear search.
- Trace a linear search and count the comparisons, for both a successful and an unsuccessful search.
- Write linear search in pseudocode and Python so that it returns the index or -1.
- Explain why
return -1belongs after the loop, not inside it. - Decide when linear search is the right tool.
- 说明线性查找的前提条件(无)以及最好和最坏情况。
- 追踪线性查找并统计比较次数,包括查找成功和失败两种情况。
- 用伪代码和 Python 编写线性查找,返回索引或 -1。
- 解释为什么
return -1应放在循环之后,而不是循环之内。 - 判断何时线性查找是合适的工具。
- Works on适用于: any list, sorted or unsorted. No pre-condition required.:任意列表,有序或无序均可,无前提条件。
- Worst case最坏情况: n steps (item is at the end or not in the list at all).:n 步(目标在末尾或根本不存在)。
- Best case最好情况: 1 step (target is at index 0).:1 步(目标在索引 0 处)。
- Return value返回值: the index where the target was found, or −1 (not found).:找到目标的索引,或 −1(未找到)。
Worked Example 1: Linear search on a list of temperatures例题 1:在温度列表上线性查找
List: [14, 22, 8, 31, 19, 27, 5]. Search for target = 27. Trace the algorithm step by step.列表:[14, 22, 8, 31, 19, 27, 5]。查找目标 = 27。逐步追踪算法。
Pseudocode.伪代码。
INPUT data, target
FOR i FROM 0 TO length(data) - 1:
IF data[i] == target THEN
OUTPUT i
STOP
OUTPUT -1 # not found
Code keywords above: FOR loop, IF condition, OUTPUT result, early STOP.以上代码关键字:FOR 循环,IF 条件,OUTPUT 输出,提前 STOP 停止。
Python implementation.Python 实现。
def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i
return -1
temps = [14, 22, 8, 31, 19, 27, 5]
print(linear_search(temps, 27)) # Output: 5
Trace: index 0 (14≠27), index 1 (22≠27), index 2 (8≠27), index 3 (31≠27), index 4 (19≠27), index 5 (27==27) FOUND. Total: 6 comparisons. Worst case for 7 items would be 7.追踪:索引 0(14≠27),索引 1(22≠27),索引 2(8≠27),索引 3(31≠27),索引 4(19≠27),索引 5(27==27)找到。共 6 次比较。7 个元素的最坏情况为 7 次。
Worked Example 2: Counting comparisons and avoiding a bug例题 2:统计比较次数并避免一个错误
Search the name list ["Mia", "Raj", "Lee", "Sam", "Ana"] for "Lee" and for "Zoe". Count the comparisons each time, then explain why a version with return -1 inside the loop is wrong.在名字列表 ["Mia", "Raj", "Lee", "Sam", "Ana"] 中查找 "Lee" 和 "Zoe",分别统计比较次数,并解释为什么把 return -1 放在循环内的版本是错误的。
def linear_search_count(data, target):
comparisons = 0
for i in range(len(data)):
comparisons += 1
if data[i] == target:
return i, comparisons
return -1, comparisons
names = ["Mia", "Raj", "Lee", "Sam", "Ana"]
print(linear_search_count(names, "Lee")) # (2, 3)
print(linear_search_count(names, "Zoe")) # (-1, 5)
# Common error: return -1 inside the loop
def bad_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i
else:
return -1 # runs after the FIRST mismatch
temps = [14, 22, 8, 31, 19, 27, 5]
print(bad_search(temps, 27)) # -1 (wrong: 27 is at index 5)
print(bad_search(temps, 14)) # 0 (right only because the target is first)
Searching for "Lee" checks Mia, Raj, Lee: 3 comparisons, index 2. Searching for "Zoe" checks all 5 names without a match, so it makes 5 comparisons and returns -1. Rule of thumb: a target at index k costs k + 1 comparisons, and an absent target costs n.查找 "Lee" 依次检查 Mia、Raj、Lee:3 次比较,索引 2。查找 "Zoe" 检查全部 5 个名字都不匹配,所以 5 次比较并返回 -1。经验规则:目标在索引 k 处需要 k + 1 次比较,目标不存在则需要 n 次。
Why the bug fails: bad_search puts return -1 in the else branch, so the function returns after the very first item that does not match. It can only succeed if the target is at index 0. The correct place for return -1 is after the loop, once every item has been checked.错误原因:bad_search 把 return -1 放在 else 分支中,因此遇到第一个不匹配的元素就返回。只有目标恰好在索引 0 时才会成功。正确位置是在循环之后,也就是所有元素都检查完毕之后。
Command words: trace means show the index and the comparison at every step; write means give complete code including the not-found case; state means one short fact. Common errors: counting by index (a target at index 5 takes 6 comparisons, not 5) and putting return -1 inside the loop, which ends the search after the first mismatch.
指令词:trace(追踪)要求写出每一步的索引和比较;write(编写)要求给出完整代码,包括未找到的情况;state(陈述)只需一句简短事实。常见错误:按索引计数(目标在索引 5 需 6 次比较,不是 5 次),以及把 return -1 放在循环内,导致遇到第一个不匹配就结束查找。
A list has 40 items. What is the fewest and the most comparisons a linear search can make?一个列表有 40 个元素。线性查找最少和最多各需多少次比较?
Fewest: 1, when the target is at index 0. Most: 40, when the target is the last item or is not in the list.
最少:1 次,目标在索引 0。最多:40 次,目标是最后一个元素或不在列表中。
Search [14, 22, 8, 31, 19, 27, 5] for 8. What index is returned and how many comparisons are made?在 [14, 22, 8, 31, 19, 27, 5] 中查找 8。返回什么索引,需要多少次比较?
The index is 2. The comparisons are 14, 22, then 8, so 3 comparisons (index + 1).
索引为 2。依次比较 14、22、8,共 3 次比较(索引 + 1)。
A function loops over the whole list, adds 1 to a counter each time an item equals the target, and returns the counter. What does it return for [4, 7, 4, 9, 4] and target 4, and how many comparisons does it make?一个函数遍历整个列表,每当元素等于目标就让计数器加 1,最后返回计数器。对 [4, 7, 4, 9, 4] 和目标 4,它返回什么?共做多少次比较?
It returns 3. It always makes 5 comparisons because it never stops early. A linear search that returns the first matching index would stop after 1 comparison here.
返回 3。它总是做 5 次比较,因为从不提前停止。而返回第一个匹配索引的线性查找在这里只需 1 次比较。
Going deeper: when linear search is the right choice深入:何时线性查找是正确选择
Linear search is optimal for unsorted lists because no faster algorithm exists without pre-sorting. It is also correct for small lists (under ~20 items) where the overhead of sorting to enable binary search is not worth it. CSTA 3B-AP-11 says "Evaluate algorithms in terms of their efficiency", and the answer here is: linear search is O(n), simple to implement, and the right tool when you cannot guarantee the list is sorted or when you search only once. If you search the same large sorted list many times, sort once and switch to binary search.对于未排序列表,线性查找是最优选择,因为不预先排序就不存在更快的算法。对于小型列表(约 20 个元素以下),为启用二分查找而排序的开销也不值得。CSTA 3B-AP-11 要求"从效率方面评估算法",此处的答案是:线性查找是 O(n),实现简单,是列表无法保证有序或只查找一次时的正确工具。若需对同一大型有序列表多次查找,则一次性排序后改用二分查找。
Binary Search二分查找
- State the pre-condition for binary search (a sorted list) and explain why it is needed.
- Trace
low,midandhighat every step, for a successful and an unsuccessful search. - Write binary search in pseudocode and Python, using integer division for
mid. - Give the worst-case comparison count ⌊log₂(n)⌋ + 1 and say how it differs from the number of halvings.
- 说明二分查找的前提条件(有序列表)并解释其必要性。
- 在查找成功和失败两种情况下,追踪每一步的
low、mid和high。 - 用伪代码和 Python 编写二分查找,并用整除计算
mid。 - 给出最坏情况比较次数 ⌊log₂(n)⌋ + 1,并说明它与减半次数的区别。
- Pre-condition前提条件: list must be sorted in ascending order.:列表必须按升序排列。
- Worst case最坏情况: at most ⌊log₂(n)⌋ + 1 comparisons (that is ⌊log₂(n)⌋ halvings plus the final check). For 1,024 items: 11 comparisons. For 1,000,000 items: 20 comparisons.:最多 ⌊log₂(n)⌋ + 1 次比较(即 ⌊log₂(n)⌋ 次减半再加最后一次检查)。1024 个元素:11 次比较。100 万个元素:20 次比较。
- Strategy策略: compare target to the middle element. If target is smaller, search left half; if larger, search right half; if equal, found.:将目标与中间元素比较。若目标较小,搜索左半部分;若较大,搜索右半部分;若相等,找到。
Worked Example 3: Binary search on a sorted list例题 3:在有序列表上二分查找
Sorted list: [3, 8, 12, 17, 25, 34, 41, 55, 68, 77]. Target = 34. Trace step by step (indices 0–9).有序列表:[3, 8, 12, 17, 25, 34, 41, 55, 68, 77]。目标 = 34。逐步追踪(索引 0–9)。
Pseudocode.伪代码。
INPUT data, target
SET low TO 0
SET high TO length(data) - 1
WHILE low <= high:
SET mid TO (low + high) // 2
IF data[mid] == target THEN
OUTPUT mid
STOP
ELSE IF data[mid] < target THEN
SET low TO mid + 1
ELSE:
SET high TO mid - 1
OUTPUT -1 # not found
Code keywords: // is integer division; low/high track the current search window.代码关键字:// 为整除;low/high 跟踪当前搜索窗口。
Step-by-step trace.逐步追踪。
| Step步骤 | low | high | mid | data[mid]data[mid] | Action操作 |
|---|---|---|---|---|---|
| 1 | 0 | 9 | 4 | 25 | 25 < 34 → low = 525 < 34 → low = 5 |
| 2 | 5 | 9 | 7 | 55 | 55 > 34 → high = 655 > 34 → high = 6 |
| 3 | 5 | 6 | 5 | 34 | 34 == 34 → FOUND at index 534 == 34 → 在索引 5 找到 |
Python implementation.Python 实现。
def binary_search(data, target):
low, high = 0, len(data) - 1
while low <= high:
mid = (low + high) // 2
if data[mid] == target:
return mid
elif data[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
nums = [3, 8, 12, 17, 25, 34, 41, 55, 68, 77]
print(binary_search(nums, 34)) # Output: 5
3 comparisons to find 34 in a 10-element list. Linear search would need 6. The advantage grows dramatically for larger lists: a million items takes at most 20 binary-search comparisons vs up to 1,000,000 linear comparisons.在 10 个元素的列表中找到 34 只需 3 次比较;线性查找需要 6 次。对于更大的列表,优势急剧增加:100 万个元素最多需要 20 次二分比较,而线性查找最多需要 100 万次。
low, mid and high, and dashed grey cells have been eliminated. The pointer values are printed in the row headings; the window shrinks from 10 cells to 5, then 2, then the found cell.图 1. 在例题 3 的有序列表中二分查找 34。每一行是一步:L、M、H 分别标出 low、mid、high,虚线灰色单元格已被淘汰。指针取值印在各行标题中;窗口从 10 个单元格缩小到 5 个,再到 2 个,最后是找到的单元格。Worked Example 4: An unsuccessful search and the worst case例题 4:查找失败与最坏情况
Binary search the sorted list [2, 5, 9, 14, 20, 27, 33, 41] for the target 30, which is not in the list. Trace every step, then state the worst-case number of comparisons for 8 items.在有序列表 [2, 5, 9, 14, 20, 27, 33, 41] 中二分查找目标 30(不在列表中)。追踪每一步,然后说明 8 个元素的最坏情况比较次数。
Sorted list: [2, 5, 9, 14, 20, 27, 33, 41] (8 items, indices 0 to 7). Target 30.有序列表:[2, 5, 9, 14, 20, 27, 33, 41](8 个元素,索引 0 至 7)。目标 30。
| Step步骤 | low | high | mid | data[mid] | Action操作 |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 14 | 14 < 30, so low = 414 < 30, so low = 4 |
| 2 | 4 | 7 | 5 | 27 | 27 < 30, so low = 627 < 30, so low = 6 |
| 3 | 6 | 7 | 6 | 33 | 33 > 30, so high = 533 > 30, so high = 5 |
| 4 | 6 | 5 | - | - | low > high: window empty, return -1low > high:窗口为空,返回 -1 |
def binary_search_trace(data, target):
low, high = 0, len(data) - 1
probes = 0
while low <= high:
mid = (low + high) // 2
probes += 1
print("low", low, "high", high, "mid", mid, "value", data[mid])
if data[mid] == target:
return mid, probes
elif data[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1, probes
nums = [2, 5, 9, 14, 20, 27, 33, 41]
print(binary_search_trace(nums, 30))
The search stops when low > high, which means no item is left to check. It made 3 comparisons. The worst case for 8 items is ⌊log₂(8)⌋ + 1 = 4 comparisons: searching for 41 takes 4 (mids 3, 5, 6, 7). In general the worst case is ⌊log₂(n)⌋ + 1 comparisons, which is one more than the ⌊log₂(n)⌋ halvings.当 low > high 时查找停止,表示没有元素可检查。本例做了 3 次比较。8 个元素的最坏情况是 ⌊log₂(8)⌋ + 1 = 4 次比较:查找 41 需要 4 次(mid 依次为 3、5、6、7)。一般地,最坏情况是 ⌊log₂(n)⌋ + 1 次比较,比 ⌊log₂(n)⌋ 次减半多一次。
Two classic bugs: mid = (low + high) / 2 gives a float in Python 3, and using it as an index raises TypeError; use //. Writing low = mid instead of low = mid + 1 can leave the window unchanged, so the loop never ends.两个经典错误:mid = (low + high) / 2 在 Python 3 中得到浮点数,用作索引会引发 TypeError,应使用 //。把 low = mid + 1 写成 low = mid 可能使窗口保持不变,循环永远不会结束。
State the pre-condition (sorted list) before you describe the steps. In a trace, show low, high and mid on every row, and say which count you give: comparisons (⌊log₂(n)⌋ + 1) or halvings (⌊log₂(n)⌋). Common errors: computing mid with / instead of //, and writing low = mid instead of low = mid + 1.
先陈述前提条件(有序列表),再描述步骤。追踪时每一行都写出 low、high 和 mid,并说明给出的是哪种计数:比较次数(⌊log₂(n)⌋ + 1)还是减半次数(⌊log₂(n)⌋)。常见错误:用 / 而不是 // 计算 mid,以及把 low = mid + 1 写成 low = mid。
List [4, 9, 15, 22, 31, 40, 52, 63, 70], target 52. Give mid and data[mid] at each step and the result.列表 [4, 9, 15, 22, 31, 40, 52, 63, 70],目标 52。写出每一步的 mid 和 data[mid] 以及结果。
Step 1: low 0, high 8, mid 4, value 31; 31 < 52 so low = 5. Step 2: low 5, high 8, mid 6, value 52, found. The result is index 6 after 2 comparisons.
第 1 步:low 0,high 8,mid 4,值 31;31 < 52,所以 low = 5。第 2 步:low 5,high 8,mid 6,值 52,找到。结果是索引 6,共 2 次比较。
Same list, target 10. What is returned and how many comparisons are made?同一列表,目标 10。返回什么,做了多少次比较?
Mid 4 (31 > 10) so high = 3; mid 1 (9 < 10) so low = 2; mid 2 (15 > 10) so high = 1. Now low 2 > high 1, so it returns -1 after 3 comparisons.
mid 4(31 > 10),high = 3;mid 1(9 < 10),low = 2;mid 2(15 > 10),high = 1。此时 low 2 > high 1,共 3 次比较后返回 -1。
What is the worst-case number of comparisons for 1,000 items, and for 2,000 items?1000 个元素和 2000 个元素的最坏情况比较次数各是多少?
For 1,000 items: ⌊log₂(1000)⌋ + 1 = 9 + 1 = 10, because 2⁹ = 512 ≤ 1000 < 1024. For 2,000 items: 10 + 1 = 11, because 1024 ≤ 2000 < 2048. Doubling the list adds one comparison.
1000 个元素:⌊log₂(1000)⌋ + 1 = 9 + 1 = 10,因为 2⁹ = 512 ≤ 1000 < 1024。2000 个元素:10 + 1 = 11,因为 1024 ≤ 2000 < 2048。列表翻倍只多一次比较。
Going deeper: AP CSP pseudocode for binary search深入:AP CSP 二分查找伪代码
AP CSP topic 3.11 presents binary search in the College Board's own pseudocode notation. Key differences from the pseudocode in this guide: assignment uses ← (arrow), lists are 1-indexed (first element is index 1, not 0), and display uses DISPLAY(). The logic is identical; only the surface notation changes. Practice translating the algorithm above into College Board pseudocode as practice. ICS4U C2.2 and CSE3110 outcome 1.5.4 go further: both require formal comparison of computational efficiency (step-count analysis), which maps to the Big-O section (§3) of this guide.AP CSP 主题 3.11 使用 College Board 自己的伪代码表示法呈现二分查找。与本指南伪代码的主要区别:赋值用 ←(箭头),列表从 1 开始索引(第一个元素索引为 1,不是 0),显示用 DISPLAY()。逻辑相同,仅表面符号不同。将上述算法翻译为 College Board 伪代码作为练习。ICS4U C2.2 和 CSE3110 结果 1.5.4 更进一步:两者均要求对计算效率进行正式比较(步骤数分析),对应本指南第 3 节(大O)。
Introduction to Algorithm Efficiency (Big-O Concept)算法效率初步(大O概念)
- Define algorithm efficiency as how the step count grows with the input size n.
- Classify linear search as O(n), binary search as O(log n) and two nested loops over n items as O(n²).
- Compare worst-case step counts for linear and binary search for a given n, saying which count is used.
- Decide whether sorting first is worth it by comparing total costs.
- 将算法效率定义为步骤数随输入规模 n 增长的方式。
- 将线性查找归类为 O(n),二分查找归类为 O(log n),对 n 个元素的两层嵌套循环归类为 O(n²)。
- 比较给定 n 时线性查找和二分查找的最坏情况步骤数,并说明使用哪种计数。
- 通过比较总代价,判断先排序是否划算。
- Linear search step count线性查找步骤数: proportional to n (the list size). Double the list → double the steps. We say it is O(n).:与 n(列表大小)成正比。列表翻倍 → 步骤翻倍。称为 O(n)。
- Binary search step count二分查找步骤数: proportional to log₂(n). Double the list → only one extra step. We say it is O(log n).:与 log₂(n) 成正比。列表翻倍 → 只多一步。称为 O(log n)。
- Concrete comparison具体比较: for 1,000,000 items: linear search up to 1,000,000 steps; binary search at most 20 steps. O(log n) is dramatically better for large n.:100 万个元素:线性查找最多 100 万步;二分查找最多 20 步。对于大 n,O(log n) 显著更优。
Worked Example 5: Comparing search step counts例题 5:比较查找步骤数
For list sizes n = 8, 16, 64, 1024, 1,000,000, calculate the worst-case step count for linear search and binary search side by side.对于列表大小 n = 8、16、64、1024、1,000,000,分别计算线性查找和二分查找的最坏情况步骤数。
| n | Linear (worst case)线性(最坏) | Binary (worst case, comparisons)二分(最坏,比较次数) | Ratio比值 |
|---|---|---|---|
| 8 | 8 | 4 | 2× |
| 16 | 16 | 5 | 3.2× |
| 64 | 64 | 7 | 9.1× |
| 1,024 | 1,024 | 11 | 93.1× |
| 1,000,000 | 1,000,000 | 20 | 50,000× |
As n grows, the ratio between linear and binary search becomes enormous. The binary column counts comparisons (⌊log₂(n)⌋ + 1); the number of halvings is one less. This is the power of O(log n) vs O(n). The cost: binary search requires the list to be sorted first. Sorting itself takes time (O(n²) for simple sorts, O(n log n) for advanced sorts: see §7).随着 n 增大,线性与二分查找之间的比值变得极大。二分列统计的是比较次数(⌊log₂(n)⌋ + 1);减半次数比它少一次。这就是 O(log n) 对比 O(n) 的威力。代价是:二分查找要求列表必须先排序。排序本身需要时间(简单排序 O(n²),高级排序 O(n log n),见 §7)。
Worked Example 6: Is sorting first worth it?例题 6:先排序划算吗?
A list has 1,000 items. Sorting with bubble sort costs up to 499,500 comparisons. After sorting, binary search can be used. How many lookups are needed before sort-then-binary-search beats repeated linear search?一个列表有 1000 个元素。冒泡排序最多需要 499,500 次比较,排序之后可以使用二分查找。至少要查找多少次,先排序再二分查找才比重复线性查找更省?
Use worst-case counts. Costs: bubble sort on 1,000 items needs 1000 × 999 / 2 = 499,500 comparisons, once. Each linear search costs at most 1,000. Each binary search costs at most 10 comparisons (⌊log₂(1000)⌋ + 1). Each lookup therefore saves 1,000 - 10 = 990 comparisons, and the sort pays for itself when 990 × k > 499,500.使用最坏情况计数。代价:对 1000 个元素做冒泡排序一次需要 1000 × 999 / 2 = 499,500 次比较。每次线性查找最多 1000 次。每次二分查找最多 10 次比较(⌊log₂(1000)⌋ + 1)。因此每次查找节省 1000 - 10 = 990 次比较,当 990 × k > 499,500 时排序的代价就收回了。
n = 1000
sort_cost = n * (n - 1) // 2 # bubble sort, worst-case comparisons
linear_cost = n # linear search, worst case
binary_cost = n.bit_length() # binary search comparisons: floor(log2 n) + 1
saving = linear_cost - binary_cost
searches = sort_cost // saving + 1
print(sort_cost, binary_cost, saving, searches)
The output 499500 10 990 505 means k must be at least 505. With 504 lookups, linear search costs 504,000 and sort-then-binary costs 499,500 + 5,040 = 504,540 (sorting loses). With 505 lookups, linear costs 505,000 and sort-then-binary costs 499,500 + 5,050 = 504,550 (sorting wins). With a faster sort of about n log₂(n) steps the break-even point comes much sooner, which is why real programs use the built-in sort (section 7).输出 499500 10 990 505 表示 k 至少为 505。查找 504 次时,线性查找共 504,000,先排序再二分共 499,500 + 5,040 = 504,540(排序更差)。查找 505 次时,线性共 505,000,先排序再二分共 499,500 + 5,050 = 504,550(排序更好)。如果用约 n log₂(n) 步的快速排序,盈亏平衡点会早得多,这就是实际程序使用内置排序的原因(第 7 节)。
Compare means give both algorithms side by side with numbers for the same n; justify means give the count, not only the Big-O label. Say what the pre-condition costs (binary search needs sorted data). Common errors: calling O(log n) better without mentioning that sorting may be needed first, and mixing comparisons and halvings in one table.
Compare(比较)要求把两个算法放在一起,用同一个 n 的数字比较;justify(论证)要求给出具体计数,而不只是大O标签。要说明前提条件的代价(二分查找需要有序数据)。常见错误:只说 O(log n) 更好而不提可能需要先排序,以及在同一张表里混用比较次数和减半次数。
Binary search needs 11 comparisons in the worst case for 2,000 items. How many does it need for 4,000 items, and how many does linear search need for each size?二分查找在 2000 个元素时最坏需要 11 次比较。4000 个元素需要多少次?线性查找在两种规模下各需多少次?
Binary search: 12 comparisons for 4,000 items (doubling n adds one). Linear search: up to 2,000 and up to 4,000 comparisons (doubling n doubles the steps).
二分查找:4000 个元素需要 12 次比较(n 翻倍只多一次)。线性查找:分别最多 2000 次和 4000 次(n 翻倍则步骤翻倍)。
What does count equal at the end, and what is the Big-O class? The code is count = 0, then for i in range(6): containing for j in range(6): containing count += 1.循环结束时 count 等于多少?大O类别是什么?代码:count = 0,然后 for i in range(6): 内含 for j in range(6):,其中含 count += 1。
count is 6 × 6 = 36. With n in place of 6 the body runs n × n times, so the class is O(n²).
count 等于 6 × 6 = 36。把 6 换成 n,循环体执行 n × n 次,所以类别是 O(n²)。
A program searches an unsorted list of 1,000 items exactly once. Is it worth bubble-sorting first so that binary search can be used?一个程序只在 1000 个元素的无序列表中查找一次。先用冒泡排序再二分查找划算吗?
No. One linear search costs at most 1,000 comparisons. Bubble sort alone costs up to 499,500 comparisons, so sorting first only pays off after many lookups (505 in Worked Example 6).
不划算。一次线性查找最多 1000 次比较,而冒泡排序本身最多就要 499,500 次比较,所以要查找很多次才值得先排序(例题 6 中是 505 次)。
Going deeper: Big-O notation formal Honors: ICS4U C2 / CSE3110深入:大O表示法正式版 荣誉:ICS4U C2 / CSE3110
Computer scientists use Big-O notation to describe how an algorithm's step count grows with input size n, ignoring constant factors and lower-order terms. Common classes: O(1) constant (same steps regardless of n, e.g., read index 0); O(log n) logarithmic (binary search); O(n) linear (linear search); O(n log n) linearithmic (efficient sorts: merge sort, quicksort); O(n²) quadratic (simple comparison sorts: bubble, selection, insertion). Ontario ICS4U C2.2/C2.3 and Alberta CSE3110 outcomes 1.5.4/1.6.5 require formal comparison of search and sort efficiencies using this framework. For ICS4U/CSE3110 students: classify each algorithm in this guide by its Big-O, then verify the classification with the step-count table above.计算机科学家使用大O表示法描述算法步骤数随输入大小 n 增长的方式,忽略常数因子和低阶项。常见类别:O(1) 常数(步骤数与 n 无关,如读取索引 0);O(log n) 对数(二分查找);O(n) 线性(线性查找);O(n log n) 线性对数(高效排序,归并排序、快速排序);O(n²) 二次(简单比较排序,冒泡、选择、插入)。安大略 ICS4U C2.2/C2.3 和阿尔伯塔 CSE3110 结果 1.5.4/1.6.5 要求使用此框架对查找和排序效率进行正式比较。ICS4U/CSE3110 学生:为本指南中每个算法分类其大O,然后用上表的步骤数验证分类。
Bubble Sort冒泡排序
- Describe bubble sort and state what is guaranteed after each pass (the largest unsorted item is in place).
- Trace bubble sort pass by pass, counting comparisons and swaps.
- State the worst case n(n - 1)/2 comparisons and the O(n) best case of the early-exit version.
- Write bubble sort and the early-exit version in Python.
- 描述冒泡排序,并说明每遍之后得到的保证(最大的未排序元素已就位)。
- 逐遍追踪冒泡排序,并统计比较和交换次数。
- 陈述最坏情况 n(n - 1)/2 次比较,以及带提前退出版本的 O(n) 最好情况。
- 用 Python 编写冒泡排序及其提前退出版本。
- Passes遍数: after each pass, the largest unsorted element “bubbles up” to its correct position at the right end.:每遍后,最大的未排序元素"冒泡"到右端的正确位置。
- Worst case最坏情况: O(n²) comparisons (for n=10: up to 45 comparisons; for n=100: up to 4,950).:O(n²) 次比较,n=10 时最多 45 次;n=100 时最多 4950 次。
- Swap in PythonPython 中的交换:
a, b = b, aswaps two variables. No temporary variable needed.:a, b = b, a交换两个变量,无需临时变量。
Worked Example 7: Bubble sort on a 5-element list例题 7:5 个元素列表的冒泡排序
Sort [5, 3, 8, 1, 4] into ascending order using bubble sort. Trace each pass.用冒泡排序将 [5, 3, 8, 1, 4] 排成升序,追踪每遍。
Pseudocode.伪代码。
FOR pass FROM 0 TO length(data) - 2:
FOR i FROM 0 TO length(data) - 2 - pass:
IF data[i] > data[i+1] THEN
SWAP data[i] AND data[i+1]
Inner loop compares adjacent pairs; outer loop repeats for each pass. After each pass, the boundary shrinks by 1 (the rightmost element is now sorted).内层循环比较相邻元素;外层循环对每遍重复。每遍后边界缩小 1(最右侧元素已排好)。
Pass-by-pass trace.逐遍追踪。
| Pass遍 | List after pass该遍后列表 | Swaps交换次数 |
|---|---|---|
| Start初始 | [5, 3, 8, 1, 4] | – |
| 1 | [3, 5, 1, 4, 8] | 3 |
| 2 | [3, 1, 4, 5, 8] | 2 |
| 3 | [1, 3, 4, 5, 8] | 1 |
| 4 | [1, 3, 4, 5, 8] | 0 → sorted |
Python implementation.Python 实现。
def bubble_sort(data):
n = len(data)
for pass_num in range(n - 1):
for i in range(n - 1 - pass_num):
if data[i] > data[i + 1]:
data[i], data[i + 1] = data[i + 1], data[i] # swap
return data
print(bubble_sort([5, 3, 8, 1, 4])) # Output: [1, 3, 4, 5, 8]
The data[i], data[i+1] = data[i+1], data[i] is the Python idiom for swapping two elements.data[i], data[i+1] = data[i+1], data[i] 是 Python 交换两个元素的惯用写法。
Worked Example 8: Counting work and the early exit例题 8:统计工作量与提前退出
Run the early-exit bubble sort on [2, 1, 3, 4, 5], on the sorted list [1, 2, 3, 4, 5] and on the reversed list [5, 4, 3, 2, 1]. Record comparisons, swaps and passes, and explain the best and worst cases.对 [2, 1, 3, 4, 5]、已排序列表 [1, 2, 3, 4, 5] 和逆序列表 [5, 4, 3, 2, 1] 运行带提前退出的冒泡排序。记录比较、交换和遍数,并解释最好和最坏情况。
def bubble_sort_counted(data):
data = data[:] # work on a copy
comparisons = swaps = passes = 0
n = len(data)
for pass_num in range(n - 1):
passes += 1
swapped = False
for i in range(n - 1 - pass_num):
comparisons += 1
if data[i] > data[i + 1]:
data[i], data[i + 1] = data[i + 1], data[i]
swaps += 1
swapped = True
if not swapped:
break # no swaps: already sorted
return data, comparisons, swaps, passes
for lst in ([2, 1, 3, 4, 5], [1, 2, 3, 4, 5], [5, 4, 3, 2, 1]):
print(lst, bubble_sort_counted(lst))
| List列表 | Comparisons比较 | Swaps交换 | Passes遍数 |
|---|---|---|---|
| [2, 1, 3, 4, 5] | 7 | 1 | 2 |
| [1, 2, 3, 4, 5] | 4 | 0 | 1 |
| [5, 4, 3, 2, 1] | 10 | 10 | 4 |
For [2, 1, 3, 4, 5]: pass 1 makes 4 comparisons and 1 swap (2 and 1), giving [1, 2, 3, 4, 5]; pass 2 makes 3 comparisons and no swap, so the loop exits: 4 + 3 = 7 comparisons. For a sorted list one pass of n - 1 = 4 comparisons is enough, which is the O(n) best case. The reversed list is the worst case: every comparison swaps, giving n(n - 1)/2 = 10 comparisons and 10 swaps.对于 [2, 1, 3, 4, 5]:第 1 遍做 4 次比较和 1 次交换(2 与 1),得到 [1, 2, 3, 4, 5];第 2 遍做 3 次比较且没有交换,循环退出:共 4 + 3 = 7 次比较。已排序的列表只需一遍 n - 1 = 4 次比较,这就是 O(n) 的最好情况。逆序列表是最坏情况:每次比较都交换,共 n(n - 1)/2 = 10 次比较和 10 次交换。
A trace question wants the list after every pass, not only the final list. State what is final after pass k: the k largest items. Common errors: forgetting that the inner loop shortens each pass (n - 1 - pass), which gives wrong comparison counts, and calling plain bubble sort O(n) in the best case; only the early-exit version is.
trace(追踪)题要求写出每一遍之后的列表,而不只是最终列表。要说明第 k 遍之后已就位的是什么:最大的 k 个元素。常见错误:忘记内层循环每遍缩短(n - 1 - pass)而得到错误的比较次数,以及把普通冒泡排序的最好情况说成 O(n);只有带提前退出的版本才是。
Trace one and then two passes of bubble sort on [6, 2, 5, 1, 4]. Give the list after each pass.对 [6, 2, 5, 1, 4] 追踪一遍和两遍冒泡排序,写出每遍之后的列表。
Pass 1 swaps 6 with 2, 5, 1, 4 in turn: [2, 5, 1, 4, 6] (4 swaps). Pass 2 compares (2,5) no swap, (5,1) swap, (5,4) swap: [2, 1, 4, 5, 6]. The two largest items, 5 and 6, are now in place.
第 1 遍:6 依次与 2、5、1、4 交换,得到 [2, 5, 1, 4, 6](4 次交换)。第 2 遍:(2,5) 不交换,(5,1) 交换,(5,4) 交换,得到 [2, 1, 4, 5, 6]。最大的两个元素 5 和 6 已就位。
How many comparisons and passes does the early-exit version make on the sorted list [1, 2, 3, 4, 5, 6]?带提前退出的版本对已排序列表 [1, 2, 3, 4, 5, 6] 需要多少次比较和多少遍?
5 comparisons in 1 pass (n - 1 comparisons, no swaps), then it exits. This is the O(n) best case.
1 遍共 5 次比较(n - 1 次比较,无交换),然后退出。这就是 O(n) 的最好情况。
For n = 8, what is the largest number of comparisons bubble sort can make, and which input gives the same number of swaps?n = 8 时,冒泡排序最多做多少次比较?哪种输入的交换次数与之相同?
n(n - 1)/2 = 8 × 7 / 2 = 28 comparisons. A list in reverse order makes 28 swaps as well, because every comparison finds a pair out of order.
n(n - 1)/2 = 8 × 7 / 2 = 28 次比较。逆序列表的交换次数也是 28,因为每次比较都发现一对逆序元素。
Going deeper: optimised bubble sort with early-exit flag深入:带提前退出标志的优化冒泡排序
Standard bubble sort always runs all n-1 passes even if the list becomes sorted early. An optimised version adds a swapped flag: if a whole pass makes zero swaps, the list is sorted and the outer loop can exit early. Best case for optimised bubble sort is O(n): one pass on an already-sorted list. This is an example of the CSTA 3B-AP-11 principle: "Evaluate algorithms in terms of their efficiency", and then improve them. CSE3110 outcome 1.6.5 requires comparing sorts by computational efficiency, which includes this kind of optimisation analysis.标准冒泡排序总是运行全部 n-1 遍,即使列表提前已排好。优化版添加 swapped(已交换)标志:若某遍未发生任何交换,列表已排好,外层循环可提前退出。优化冒泡排序最好情况为 O(n),对已排序列表只需一遍。这是 CSTA 3B-AP-11 原则"从效率方面评估算法"的体现,然后加以改进。CSE3110 结果 1.6.5 要求按计算效率比较排序,包括此类优化分析。
def bubble_sort_optimised(data):
n = len(data)
for pass_num in range(n - 1):
swapped = False
for i in range(n - 1 - pass_num):
if data[i] > data[i + 1]:
data[i], data[i + 1] = data[i + 1], data[i]
swapped = True
if not swapped:
break # list is already sorted
return data
Selection Sort选择排序
- Describe selection sort and state what is guaranteed after k passes (the k smallest items are in place).
- Trace selection sort pass by pass, recording the minimum found and its index.
- State that it always makes n(n - 1)/2 comparisons and at most n - 1 exchanges.
- Explain when having fewer exchanges matters.
- 描述选择排序,并说明 k 遍之后的保证(最小的 k 个元素已就位)。
- 逐遍追踪选择排序,记录找到的最小值及其索引。
- 陈述它总是做 n(n - 1)/2 次比较,且最多 n - 1 次交换。
- 解释交换次数较少在什么情况下重要。
- Swaps交换次数: at most n-1 swaps (one swap step per pass, and some move nothing), far fewer than bubble sort.:最多 n-1 次交换(每遍一次交换步骤,有些并不移动元素),远少于冒泡排序。
- Comparisons比较次数: still O(n²) comparisons in all cases (always scans the full remaining portion to find the minimum).:所有情况下仍为 O(n²) 次比较(总是扫描完整的剩余部分以找最小值)。
- Position定位: after pass k, the first k elements are in their final sorted positions.:第 k 遍后,前 k 个元素处于最终排序位置。
Worked Example 9: Selection sort on a 5-element list例题 9:5 个元素列表的选择排序
Sort [5, 3, 8, 1, 4] using selection sort. Trace each pass.用选择排序将 [5, 3, 8, 1, 4] 排序,追踪每遍。
Pseudocode.伪代码。
FOR i FROM 0 TO length(data) - 2:
SET min_idx TO i
FOR j FROM i+1 TO length(data) - 1:
IF data[j] < data[min_idx] THEN
SET min_idx TO j
SWAP data[i] AND data[min_idx]
Inner loop finds the minimum in the unsorted portion (indices i to end). Outer loop places it at position i.内层循环在未排序部分(索引 i 到末尾)中找最小值;外层循环将其放到位置 i。
Pass-by-pass trace.逐遍追踪。
| Pass遍 | Min found找到最小值 | List after pass该遍后列表 |
|---|---|---|
| Start初始 | – | [5, 3, 8, 1, 4] |
| 1 (i=0) | 1 (idx 3) | [1, 3, 8, 5, 4] |
| 2 (i=1) | 3 (idx 1) | [1, 3, 8, 5, 4] |
| 3 (i=2) | 4 (idx 4) | [1, 3, 4, 5, 8] |
| 4 (i=3) | 5 (idx 3) | [1, 3, 4, 5, 8] |
Python implementation.Python 实现。
def selection_sort(data):
n = len(data)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if data[j] < data[min_idx]:
min_idx = j
data[i], data[min_idx] = data[min_idx], data[i] # swap
return data
print(selection_sort([5, 3, 8, 1, 4])) # Output: [1, 3, 4, 5, 8]
The swap line runs exactly n-1 = 4 times for 5 elements, but passes 2 and 4 swap an element with itself, so only 2 real exchanges happen (5 with 1 in pass 1, 8 with 4 in pass 3) and 4 elements change place. Bubble sort on the same list made 3+2+1+0 = 6 swaps. Fewer swaps is better when writes to memory are expensive.代码中的交换语句对 5 个元素恰好执行 n-1 = 4 次,但第 2 遍和第 4 遍是元素与自身交换,所以实际只发生 2 次真正的交换(第 1 遍 5 与 1,第 3 遍 8 与 4),共有 4 个元素换了位置。相同列表的冒泡排序进行了 3+2+1+0 = 6 次交换。当内存写入代价高时,更少交换更好。
Worked Example 10: Comparisons versus exchanges例题 10:比较次数与交换次数
Selection sort [64, 25, 12, 22, 11]. Trace each pass, then count the comparisons and the exchanges. Repeat the count for the already sorted list [1, 2, 3, 4, 5].对 [64, 25, 12, 22, 11] 做选择排序。追踪每一遍,然后统计比较和交换次数。再对已排序列表 [1, 2, 3, 4, 5] 重复统计。
Start: [64, 25, 12, 22, 11].初始:[64, 25, 12, 22, 11]。
| Pass遍 | Min found找到最小值 | List after pass该遍后列表 | Exchange?是否交换 |
|---|---|---|---|
| 1 (i=0) | 11 (idx 4)11(索引 4) | [11, 25, 12, 22, 64] | yes: 64 and 11是:64 与 11 |
| 2 (i=1) | 12 (idx 2)12(索引 2) | [11, 12, 25, 22, 64] | yes: 25 and 12是:25 与 12 |
| 3 (i=2) | 22 (idx 3)22(索引 3) | [11, 12, 22, 25, 64] | yes: 25 and 22是:25 与 22 |
| 4 (i=3) | 25 (idx 3)25(索引 3) | [11, 12, 22, 25, 64] | no: already in place否:已在原位 |
def selection_sort_counted(data):
data = data[:]
comparisons = exchanges = 0
for i in range(len(data) - 1):
min_idx = i
for j in range(i + 1, len(data)):
comparisons += 1
if data[j] < data[min_idx]:
min_idx = j
if min_idx != i: # skip the self-swap
data[i], data[min_idx] = data[min_idx], data[i]
exchanges += 1
return data, comparisons, exchanges
print(selection_sort_counted([64, 25, 12, 22, 11])) # ([11, 12, 22, 25, 64], 10, 3)
print(selection_sort_counted([1, 2, 3, 4, 5])) # ([1, 2, 3, 4, 5], 10, 0)
Each pass scans the whole unsorted part to find the minimum: 4 + 3 + 2 + 1 = 10 comparisons, whatever the order of the data. The sorted list also needs 10 comparisons, because the algorithm cannot know the minimum is already in place until it has looked at every remaining item. Only the exchanges change: 3 here, and 0 for the sorted list.每一遍都要扫描整个未排序部分来找最小值:4 + 3 + 2 + 1 = 10 次比较,与数据顺序无关。已排序列表同样需要 10 次比较,因为算法在看完所有剩余元素之前无法知道最小值已在原位。只有交换次数会变化:本例是 3 次,已排序列表是 0 次。
When asked to trace selection sort, show the minimum found and its index for each pass. Give comparisons and exchanges separately: comparisons are always n(n - 1)/2, exchanges at most n - 1. Common errors: expecting selection sort to run faster on sorted input (it does not) and calling it stable (it is not in general).
被要求追踪选择排序时,写出每一遍找到的最小值及其索引。比较和交换要分开说:比较总是 n(n - 1)/2 次,交换最多 n - 1 次。常见错误:以为选择排序在已排序输入上会更快(不会),以及说它是稳定的(一般不是)。
Trace selection sort on [7, 3, 9, 2], giving the list after each pass.对 [7, 3, 9, 2] 追踪选择排序,写出每遍之后的列表。
Pass 1: minimum 2 at index 3, swap with 7: [2, 3, 9, 7]. Pass 2: minimum 3 is already at index 1: [2, 3, 9, 7]. Pass 3: minimum 7 at index 3, swap with 9: [2, 3, 7, 9].
第 1 遍:最小值 2 在索引 3,与 7 交换:[2, 3, 9, 7]。第 2 遍:最小值 3 已在索引 1:[2, 3, 9, 7]。第 3 遍:最小值 7 在索引 3,与 9 交换:[2, 3, 7, 9]。
How many comparisons does selection sort make for n = 8, and what is the most exchanges it can make?n = 8 时选择排序做多少次比较?最多做多少次交换?
8 × 7 / 2 = 28 comparisons. At most n - 1 = 7 exchanges, one per pass.
8 × 7 / 2 = 28 次比较。最多 n - 1 = 7 次交换,每遍一次。
Why does selection sort still make 15 comparisons on an already sorted list of 6 items?为什么选择排序在已排序的 6 个元素列表上仍然做 15 次比较?
Each pass must scan the whole unsorted part to be sure of the minimum: 5 + 4 + 3 + 2 + 1 = 15. Nothing in the algorithm can stop early, so sorted input saves exchanges (0) but not comparisons.
每一遍都必须扫描整个未排序部分才能确定最小值:5 + 4 + 3 + 2 + 1 = 15。算法中没有可以提前停止的机制,所以有序输入只能节省交换(0 次),不能节省比较。
Insertion Sort插入排序
- Describe insertion sort with the playing-card analogy and explain shifting rather than swapping.
- Trace insertion sort, writing the key, the shifts and the list after each insertion.
- State the best case (sorted: n - 1 comparisons, 0 shifts) and the worst case (reversed: n(n - 1)/2).
- Explain why insertion sort suits nearly sorted data.
- 用扑克牌类比描述插入排序,并解释为什么是移位而不是交换。
- 追踪插入排序,写出 key、移位情况以及每次插入后的列表。
- 陈述最好情况(已排序:n - 1 次比较、0 次移位)和最坏情况(逆序:n(n - 1)/2)。
- 解释为什么插入排序适合接近有序的数据。
- Analogy类比: like sorting a hand of playing cards: pick up one card at a time and slide it into the right position among already-sorted cards.:如同整理一手扑克牌:一次拿起一张,插入已排好牌的正确位置。
- Best case最好情况: O(n) when the list is already sorted (no shifts needed, so just one comparison per element).:O(n),当列表已排好时(无需移位,因此每个元素只需一次比较)。
- Worst case最坏情况: O(n²) when the list is in reverse order (every element must shift all the way left).:O(n²),当列表完全逆序时(每个元素都需一路向左移位)。
Worked Example 11: Insertion sort on a 5-element list例题 11:5 个元素列表的插入排序
Sort [5, 3, 8, 1, 4] using insertion sort. Trace each insertion step.用插入排序将 [5, 3, 8, 1, 4] 排序,追踪每次插入。
Pseudocode.伪代码。
FOR i FROM 1 TO length(data) - 1:
SET key TO data[i]
SET j TO i - 1
WHILE j >= 0 AND data[j] > key:
SET data[j+1] TO data[j] # shift right
SET j TO j - 1
SET data[j+1] TO key # insert key
key holds the element being inserted; the WHILE loop shifts larger elements one position right to make room.key 保存待插入元素;WHILE 循环将较大元素向右移一位腾出空间。
Step-by-step trace.逐步追踪。
| i | key | List after insertion插入后列表 |
|---|---|---|
| Start初始 | – | [5, 3, 8, 1, 4] |
| 1 | 3 | [3, 5, 8, 1, 4] |
| 2 | 8 | [3, 5, 8, 1, 4] |
| 3 | 1 | [1, 3, 5, 8, 4] |
| 4 | 4 | [1, 3, 4, 5, 8] |
Python implementation.Python 实现。
def insertion_sort(data):
for i in range(1, len(data)):
key = data[i]
j = i - 1
while j >= 0 and data[j] > key:
data[j + 1] = data[j] # shift element right
j -= 1
data[j + 1] = key # place key in correct position
return data
print(insertion_sort([5, 3, 8, 1, 4])) # Output: [1, 3, 4, 5, 8]
When key=8 (i=2), no shifts were needed because 8 > 5. This means nearly-sorted data has very few shifts, giving O(n) best-case performance: a property that plain bubble sort (without an early exit) and selection sort do not have.当 key=8(i=2)时,无需移位,因为 8 > 5。这意味着近乎有序数据的移位极少,达到 O(n) 最好情况性能,这是没有提前退出的普通冒泡排序和选择排序所不具备的特性。
Worked Example 12: Best, middle and worst cases例题 12:最好、一般与最坏情况
Run insertion sort on [2, 4, 6, 8, 10], on [2, 4, 1, 6, 8] and on [5, 4, 3, 2, 1]. Count comparisons and shifts for each and explain the pattern.对 [2, 4, 6, 8, 10]、[2, 4, 1, 6, 8] 和 [5, 4, 3, 2, 1] 运行插入排序。统计每个列表的比较和移位次数,并解释规律。
Count a comparison each time data[j] > key is tested, and a shift each time an item moves one place right.每测试一次 data[j] > key 计一次比较,每有一个元素向右移一位计一次移位。
def insertion_sort_counted(data):
data = data[:]
comparisons = shifts = 0
for i in range(1, len(data)):
key = data[i]
j = i - 1
while j >= 0:
comparisons += 1
if data[j] > key:
data[j + 1] = data[j] # shift right
shifts += 1
j -= 1
else:
break
data[j + 1] = key
return data, comparisons, shifts
for lst in ([2, 4, 6, 8, 10], [2, 4, 1, 6, 8], [5, 4, 3, 2, 1]):
print(lst, insertion_sort_counted(lst))
| List列表 | Comparisons比较 | Shifts移位 |
|---|---|---|
| [2, 4, 6, 8, 10] | 4 | 0 |
| [2, 4, 1, 6, 8] | 5 | 2 |
| [5, 4, 3, 2, 1] | 10 | 10 |
Sorted input: each key is compared once with its left neighbour and stays, so n - 1 = 4 comparisons and no shifts (the O(n) best case). For [2, 4, 1, 6, 8] the keys 4, 6 and 8 cost one comparison each (3 in total), while key 1 is compared with 4 and with 2, shifting both, and then reaches index 0 with no further comparison (2 in total): 3 + 2 = 5 comparisons and 2 shifts. Reversed input: the key at position i shifts past all i items before it, so 1 + 2 + 3 + 4 = 10 comparisons and 10 shifts, which is n(n - 1)/2, the O(n²) worst case.已排序输入:每个 key 只与左邻居比较一次就留在原位,所以 n - 1 = 4 次比较、0 次移位(O(n) 最好情况)。对于 [2, 4, 1, 6, 8],key 4、6、8 各需 1 次比较(共 3 次),key 1 先与 4 比较、再与 2 比较并使两者右移,然后到达索引 0,不再比较(共 2 次):3 + 2 = 5 次比较、2 次移位。逆序输入:位置 i 的 key 要越过它前面的全部 i 个元素,所以 1 + 2 + 3 + 4 = 10 次比较和 10 次移位,即 n(n - 1)/2,这是 O(n²) 的最坏情况。
Show the key, the shifts and the list after each insertion. Separate shifts (one write each) from swaps (three writes each). Common errors: starting i at 0 instead of 1, using >= instead of > in the while test (equal items then move past each other, so the sort is no longer stable), and forgetting data[j + 1] = key.
写出 key、移位情况以及每次插入后的列表。要区分移位(每次一次写入)和交换(每次三次写入)。常见错误:把 i 从 0 而不是 1 开始,while 判断中用 >= 代替 >(相等元素会互相越过,排序不再稳定),以及漏写 data[j + 1] = key。
Trace insertion sort on [4, 3, 2, 1]. How many shifts are made in total?对 [4, 3, 2, 1] 追踪插入排序。总共移位多少次?
i = 1, key 3: [3, 4, 2, 1] (1 shift). i = 2, key 2: [2, 3, 4, 1] (2 shifts). i = 3, key 1: [1, 2, 3, 4] (3 shifts). Total 1 + 2 + 3 = 6 shifts.
i = 1,key 3:[3, 4, 2, 1](1 次移位)。i = 2,key 2:[2, 3, 4, 1](2 次移位)。i = 3,key 1:[1, 2, 3, 4](3 次移位)。总计 1 + 2 + 3 = 6 次移位。
How many comparisons and shifts does insertion sort make on [2, 4, 1, 6, 8]?插入排序对 [2, 4, 1, 6, 8] 做多少次比较和移位?
5 comparisons and 2 shifts. Keys 4, 6 and 8 need 1 comparison each, and key 1 shifts 4 and 2 (2 comparisons that shift) with no further comparison once it reaches index 0.
5 次比较和 2 次移位。key 4、6、8 各需 1 次比较,key 1 使 4 和 2 右移(2 次导致移位的比较),到达索引 0 后不再比较。
A sorted list has 100 items. How many comparisons and shifts does insertion sort make, and how many comparisons for a reversed list of 100?一个已排序列表有 100 个元素。插入排序做多少次比较和移位?同样 100 个元素的逆序列表需要多少次比较?
Sorted: 99 comparisons and 0 shifts (n - 1). Reversed: 100 × 99 / 2 = 4,950 comparisons (and 4,950 shifts).
已排序:99 次比较、0 次移位(n - 1)。逆序:100 × 99 / 2 = 4950 次比较(同时 4950 次移位)。
Comparing Sorts and Using Built-in Sort排序比较与内置排序
- Compare linear search, binary search and the three simple sorts by pre-condition, best case and worst case.
- Use
sorted()and.sort()correctly, includingreverse,keyand theNonereturned by.sort(). - Combine one sort with repeated binary searches using
bisect, with a bounds check. - Explain what a stable sort is and why it matters.
- 按前提条件、最好情况和最坏情况比较线性查找、二分查找和三种简单排序。
- 正确使用
sorted()和.sort(),包括reverse、key以及.sort()返回的None。 - 用
bisect将一次排序与多次二分查找结合,并做边界检查。 - 解释什么是稳定排序以及它为什么重要。
| Algorithm算法 | Best最好 | Worst最坏 | Pre-condition前提 | Notes备注 |
|---|---|---|---|---|
| Linear search线性查找 | O(1) | O(n) | None无 | Simple; works on any list简单;适用任意列表 |
| Binary search二分查找 | O(1) | O(log n) | Sorted list已排序 | Fast on large sorted data大型有序数据很快 |
| Bubble sort冒泡排序 | O(n)* | O(n²) | None无 | *with early-exit optimisation*带提前退出优化 |
| Selection sort选择排序 | O(n²) | O(n²) | None无 | Fewest swaps; good for low-write hardware交换最少;适合少写硬件 |
| Insertion sort插入排序 | O(n) | O(n²) | None无 | Best for nearly-sorted data近乎有序数据最佳 |
Worked Example 13: Using Python's built-in sort例题 13:使用 Python 内置排序
In practice, never use bubble/selection/insertion sort on real data: use Python's built-in sorted() or .sort(). They use Timsort (O(n log n) worst case), which is dramatically faster. Know when to use each method.实践中,切勿对真实数据使用冒泡/选择/插入排序,使用 Python 内置的 sorted() 或 .sort()。它们使用 Timsort(最坏情况 O(n log n)),速度显著更快。了解何时使用各种方法。
Python built-in sort examples.Python 内置排序示例。
# sorted() returns a NEW sorted list; original unchanged
nums = [5, 3, 8, 1, 4]
sorted_nums = sorted(nums)
print(sorted_nums) # [1, 3, 4, 5, 8]
print(nums) # [5, 3, 8, 1, 4] -- unchanged
# .sort() sorts IN PLACE; modifies the original list
nums.sort()
print(nums) # [1, 3, 4, 5, 8]
# Sort descending
nums.sort(reverse=True)
print(nums) # [8, 5, 4, 3, 1]
# Sort strings or tuples by a key
students = [("Ana", 85), ("Bob", 72), ("Cara", 91)]
students.sort(key=lambda s: s[1]) # sort by score
print(students) # [('Bob', 72), ('Ana', 85), ('Cara', 91)]
The key=lambda s: s[1] tells Python to sort by the second element (the score). Use sorted() when you need to keep the original; use .sort() when you want to modify in place.key=lambda s: s[1] 告知 Python 按第二个元素(分数)排序。需要保留原列表时用 sorted();想原地修改时用 .sort()。
Combining sort + binary search in practice.实践中结合排序与二分查找。
import bisect # Python standard library for binary search on sorted lists
data = [14, 2, 31, 8, 25, 17]
data.sort() # sort first: [2, 8, 14, 17, 25, 31]
pos = bisect.bisect_left(data, 17) # binary search for 17
print(data[pos] == 17) # True (found at index 3)
The pattern: sort once with O(n log n), then use binary search O(log n) for every lookup. Far faster than repeated linear searches on large data.模式:用 O(n log n) 排序一次,再用 O(log n) 的二分查找进行每次查找。对大数据远快于重复线性查找。
Worked Example 14: Stable sorting and a safe lookup例题 14:稳定排序与安全查找
Sort the list [("Ana", 85), ("Bob", 72), ("Cara", 91), ("Dev", 85)] by score from high to low so that equal scores keep their original order. Then write a function that reports whether a value is in the sorted list [2, 8, 14, 17, 25, 31], using bisect.把列表 [("Ana", 85), ("Bob", 72), ("Cara", 91), ("Dev", 85)] 按分数从高到低排序,并使相同分数保持原有顺序。然后用 bisect 编写函数,判断某个值是否在有序列表 [2, 8, 14, 17, 25, 31] 中。
import bisect
students = [("Ana", 85), ("Bob", 72), ("Cara", 91), ("Dev", 85)]
by_score = sorted(students, key=lambda s: s[1], reverse=True)
print(by_score)
# [('Cara', 91), ('Ana', 85), ('Dev', 85), ('Bob', 72)] Ana stays before Dev
def contains(sorted_list, x):
pos = bisect.bisect_left(sorted_list, x)
return pos < len(sorted_list) and sorted_list[pos] == x
data = [2, 8, 14, 17, 25, 31]
print(contains(data, 17), contains(data, 20), contains(data, 40))
Python's sort is stable: items with equal keys keep their original relative order, so Ana (listed first) stays ahead of Dev, even with reverse=True. Stability matters when you sort by one field after another. The helper contains checks pos < len(sorted_list) first: bisect_left returns the position where the value would be inserted, which is len(sorted_list) (past the end) when the value is larger than everything, and the bounds check prevents an IndexError. For 20 it returns position 4, where the item is 25, so the equality test is False.Python 的排序是稳定的(stable):键相等的元素保持原有的相对顺序,所以先出现的 Ana 仍排在 Dev 前面,即使使用了 reverse=True。依次按多个字段排序时,稳定性很重要。辅助函数 contains 先检查 pos < len(sorted_list):bisect_left 返回该值应插入的位置,当该值比所有元素都大时位置是 len(sorted_list)(越过末尾),边界检查可避免 IndexError。对于 20,返回位置 4,该处元素是 25,所以相等判断为 False。
sorted(data) and data.sort()?在 Python 中,sorted(data) 和 data.sort() 有什么区别?sorted(data) is a built-in function that returns a new sorted list; the original data is unchanged. data.sort() is a list method that sorts the list in place (modifies data) and returns None. Use sorted() when you need both the original and the sorted version; use .sort() when you only need the sorted result.sorted(data) 是返回新排序列表的内置函数;原始 data 不变。data.sort() 是原地排序列表(修改 data)并返回 None 的列表方法。同时需要原列表和排序版本时用 sorted();只需排序结果时用 .sort()。When asked to recommend an approach, give the pre-condition, the cost of each option for the stated n, and the decision. In code questions, decide whether the original list must be kept (sorted()) or not (.sort()), and remember that .sort() returns None. Common errors: print(data.sort()) prints None, and indexing the result of bisect_left without a bounds check.
被要求推荐方案时,写出前提条件、在给定 n 下每种方案的代价以及最终决定。在代码题中,要判断是否需要保留原列表(用 sorted())还是不需要(用 .sort()),并记住 .sort() 返回 None。常见错误:print(data.sort()) 会打印 None,以及不做边界检查就用 bisect_left 的结果做索引。
What does this print? a = [3, 1, 2], then b = a.sort(), then print(a, b)下面代码输出什么?a = [3, 1, 2],然后 b = a.sort(),然后 print(a, b)
It prints [1, 2, 3] None. .sort() sorts a in place and returns None, so b is None.
输出 [1, 2, 3] None。.sort() 原地排序 a 并返回 None,所以 b 是 None。
An unsorted list has 1,024 items and will be searched 500 times. Compare linear search with sorting once and then using binary search (use the estimate n × log₂(n) for the sort).一个无序列表有 1024 个元素,要查找 500 次。比较线性查找与「先排序一次再二分查找」(排序代价用估计值 n × log₂(n))。
Linear search: 500 × 1,024 = 512,000 comparisons in the worst case. Sort once: about 1,024 × 10 = 10,240 steps, then 500 × 11 = 5,500 comparisons, about 15,740 in total. Sorting first needs roughly 30 times fewer steps.
线性查找:最坏情况 500 × 1024 = 512,000 次比较。先排序一次:约 1024 × 10 = 10,240 步,再 500 × 11 = 5,500 次比较,合计约 15,740。先排序所需步数大约少 30 倍。
For data = [2, 8, 14, 17, 25, 31], what do bisect.bisect_left(data, 20) and bisect.bisect_left(data, 40) return, and why is a bounds check needed?对 data = [2, 8, 14, 17, 25, 31],bisect.bisect_left(data, 20) 和 bisect.bisect_left(data, 40) 各返回什么?为什么需要边界检查?
They return 4 and 6. At position 4 the item is 25, not 20, so 20 is absent. Position 6 equals len(data), so data[6] would raise IndexError; checking pos < len(data) first avoids it.
分别返回 4 和 6。位置 4 的元素是 25 而不是 20,所以 20 不存在。位置 6 等于 len(data),data[6] 会引发 IndexError;先检查 pos < len(data) 可避免。
Going deeper: why Python's sort is O(n log n) not O(n²) Honors深入:为何 Python 内置排序是 O(n log n) 而非 O(n²) 荣誉
Python uses Timsort (invented by Tim Peters, 2002), a hybrid of merge sort and insertion sort. Merge sort divides the list in half, recursively sorts each half, then merges them (O(n log n) in all cases). A binary-insertion variant is used on small runs (roughly 32 to 64 elements) because its O(n) best case makes it faster than merge sort for nearly-sorted small arrays. The result: Timsort is O(n) on already-sorted data and O(n log n) in the worst case: far better than the O(n²) algorithms in this guide. ICS4U A3.6 mentions merge sort as a recursive algorithm option. CSE3310 (Recursive Algorithms 1) covers quicksort and merge sort at the Advanced level. For this course, knowing that Python's sort is O(n log n) and why it beats bubble/selection/insertion is sufficient at the ICS4U/CSE3110 level.Python 使用 Timsort(Tim Peters,2002 年发明),是归并排序与插入排序的混合体。归并排序将列表分成两半,递归排序各半部分,再合并(所有情况均为 O(n log n))。对小片段(约 32 至 64 个元素)使用插入排序的二分变体,因为其 O(n) 最好情况对近乎有序的小数组比归并排序更快。结果:Timsort 对已排序数据为 O(n),最坏情况为 O(n log n),远优于本指南的 O(n²) 算法。ICS4U A3.6 将归并排序列为递归算法选项。CSE3310(递归算法 1)在高级模块涵盖快速排序和归并排序。对本课程而言,知道 Python 内置排序是 O(n log n) 以及为何它胜过冒泡/选择/插入排序,在 ICS4U/CSE3110 级别已足够。
Exam Strategy and Common Pitfalls考试策略与常见陷阱
- State the pre-condition.陈述前提条件。 Binary search requires a sorted list. Forgetting to state this is the most common error. CSE3110 outcome 1.5.4 and ICS4U C2.2 both expect you to know the pre-condition.二分查找需要已排序列表。忘记陈述这一点是最常见的错误。CSE3110 结果 1.5.4 和 ICS4U C2.2 均要求你知道前提条件。
- Trace the algorithm with a concrete example.用具体例子追踪算法。 Always run through your answer with a 5–8 element list before submitting. A trace table catches most off-by-one boundary errors in sort algorithms.提交前始终用 5–8 个元素的列表演算答案。追踪表能发现排序算法中大多数"差一"边界错误。
- Use the correct algorithm name in Chinese and English.用中英文写出正确算法名称。 Use precise terminology: linear search, binary search, bubble sort, selection sort, insertion sort, algorithm efficiency, time complexity.使用精确术语:linear search(线性查找),binary search(二分查找),bubble sort(冒泡排序),selection sort(选择排序),insertion sort(插入排序),algorithm efficiency(算法效率),time complexity(时间复杂度)。
- State pre-condition, step count, and a number example.陈述前提条件、步骤数和数字例子。 "Binary search requires a sorted list. For n=1,024 items, binary search needs at most 11 comparisons (10 halvings plus the final check), versus 1,024 for linear search." That is two sentences and a complete answer to a typical efficiency question."二分查找需要已排序列表。对于 n=1024 个元素,二分查找最多需要 11 次比较(10 次减半加最后一次检查),而线性查找最多需要 1024 次。"两句话,就是对典型效率题的完整回答。
- Trace binary search step by step when asked.被要求时逐步追踪二分查找。 Show the low, high, mid values at each step. Never skip steps on a trace question.每步展示 low、high、mid 的值。追踪题切勿跳步。
- Know what changes after each pass.知道每遍后什么发生了变化。 Bubble sort: largest unsorted element moves to its final position. Selection sort: one minimum is placed in final position. Insertion sort: one more element joins the sorted left portion.冒泡排序:最大未排序元素移至最终位置。选择排序:一个最小值放到最终位置。插入排序:多一个元素加入有序左段。
- Compare using Big-O when asked for efficiency.被问效率时用大O比较。 All three simple sorts are O(n²) worst case for comparisons. Insertion sort is O(n) best case. Python's built-in is O(n log n) worst case. ICS4U C2.3 and CSE3110 outcome 1.6.5 name this comparison explicitly.三种简单排序比较次数最坏情况均为 O(n²)。插入排序最好情况为 O(n)。Python 内置排序最坏情况为 O(n log n)。ICS4U C2.3 和 CSE3110 结果 1.6.5 明确列出此比较。
- Show all intermediate states in a sort trace.排序追踪中展示所有中间状态。 Draw the list after every pass, not just the final result. Sort-trace questions are about the states between passes.每遍后画出列表,不只是最终结果。排序追踪题关注的正是各遍之间的状态。
- For AP CSP: use College Board pseudocode.AP CSP 使用 College Board 伪代码。 Assignment uses
←, lists are 1-indexed, useDISPLAY(). Topic 3.11 binary search and 3.17 efficiency use this notation in the College Board materials.赋值用←,列表从 1 索引,用DISPLAY()。主题 3.11 二分查找和 3.17 效率在 College Board 材料中使用此表示法。
Flashcards闪卡
Practice Quiz综合测验
Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Write pseudocode for linear search: loop through every element, return the index when found, return −1 if not found. Trace it on a 6-element unsorted list. 🇨🇦 ON ICS4U A3.2 / AB CSE3110 1.5.1编写线性查找的伪代码:遍历每个元素,找到时返回索引,未找到返回 −1。在 6 个元素的未排序列表上追踪。🇨🇦 ON ICS4U A3.2 / AB CSE3110 1.5.1
- Write pseudocode for binary search: use low/mid/high pointers, halve the search window each step, handle the not-found case. State the pre-condition (sorted list). 🇨🇦 ON ICS4U A3.2 / AB CSE3110 1.5.2 / AP CSP 3.11编写二分查找的伪代码:使用 low/mid/high 指针,每步缩小一半搜索窗口,处理未找到情况。陈述前提条件(已排序列表)。🇨🇦 ON ICS4U A3.2 / AB CSE3110 1.5.2 / AP CSP 3.11
- Compare linear and binary search by step count: state worst-case n vs ⌊log₂n⌋ + 1 comparisons, give a concrete example (e.g., 1024 items: 1024 vs 11), and state when each is preferred. 🇺🇸 AP CSP 3.17 / 🇨🇦 ICS4U C2.2 / CSE3110 1.5.4按步骤数比较线性查找和二分查找:陈述最坏情况 n vs ⌊log₂n⌋ + 1 次比较,举具体例子(如 1024 个元素:1024 vs 11),说明各自首选场景。🇺🇸 AP CSP 3.17 / 🇨🇦 ICS4U C2.2 / CSE3110 1.5.4
- Write and trace bubble sort on a 5-element list. State what is guaranteed after each pass (largest element moves to its final position). Give worst-case comparison count n(n−1)/2. 🇨🇦 ON ICS4U A3.4 / AB CSE3110 1.6.1编写并追踪 5 个元素列表的冒泡排序。陈述每遍后的保证(最大元素移至最终位置)。给出最坏情况比较次数 n(n−1)/2。🇨🇦 ON ICS4U A3.4 / AB CSE3110 1.6.1
- Write and trace selection sort on a 5-element list. State that it makes at most n−1 swaps (one minimum placed per pass) and is always O(n²) comparisons. 🇨🇦 ON ICS4U A3.4 / AB CSE3110 1.6.2编写并追踪 5 个元素列表的选择排序。陈述其最多进行 n−1 次交换(每遍放置一个最小值),且比较次数始终为 O(n²)。🇨🇦 ON ICS4U A3.4 / AB CSE3110 1.6.2
- Write and trace insertion sort on a 5-element list. Explain the shifting operation and state that its best case is O(n) on already-sorted data. 🇨🇦 ON ICS4U A3.4 / AB CSE3110 1.6.3编写并追踪 5 个元素列表的插入排序。解释移位操作,说明其在已排序数据上的最好情况为 O(n)。🇨🇦 ON ICS4U A3.4 / AB CSE3110 1.6.3
- Explain the difference between Python's sorted() and .sort(). Write a one-line call that sorts a list in descending order using .sort(reverse=True). 🇺🇸 CSTA 3B-AP-10解释 Python 的 sorted() 与 .sort() 的区别。编写一行代码用 .sort(reverse=True) 将列表降序排列。🇺🇸 CSTA 3B-AP-10
- Explain why Python's built-in sort is faster than bubble/selection/insertion sort for large n. State its worst-case complexity (O(n log n)) and name the algorithm it uses (Timsort). 🇨🇦 AB CSE3110 1.6.5 / ON ICS4U C2.3解释为何 Python 内置排序对大 n 比冒泡/选择/插入排序更快。陈述其最坏情况复杂度(O(n log n))并说出它使用的算法名称(Timsort)。🇨🇦 AB CSE3110 1.6.5 / ON ICS4U C2.3
- State verbatim (or near-verbatim) the CSTA standard 3B-AP-11 and identify which searching/sorting concept it directly maps to in this guide. 🇺🇸 CSTA 3B-AP-11逐字(或近逐字)陈述 CSTA 标准 3B-AP-11,并指出它直接映射到本指南中的哪个查找/排序概念。🇺🇸 CSTA 3B-AP-11
- State the ICS4U expectations for this unit: A3.2 (linear + binary search), A3.4 (bubble, insertion, selection sort), C2.2 (compare search efficiency), C2.3 (compare sort efficiency). 🇨🇦 ON ICS4U陈述本单元的 ICS4U 期望:A3.2(线性+二分查找)、A3.4(冒泡、插入、选择排序)、C2.2(比较查找效率)、C2.3(比较排序效率)。🇨🇦 ON ICS4U
- Honors: ICS4U C2 / CSE3110 Classify all 5 algorithms in this guide by Big-O: linear search O(n), binary search O(log n), bubble/selection/insertion sort O(n²) worst. Explain why insertion sort has O(n) best. 🇨🇦 ICS4U C2.2/C2.3 / AB CSE3110 1.5.4/1.6.5荣誉:ICS4U C2 / CSE3110 用大O对本指南中全部 5 个算法分类:线性查找 O(n),二分查找 O(log n),冒泡/选择/插入排序最坏 O(n²)。解释插入排序为何有 O(n) 最好情况。🇨🇦 ICS4U C2.2/C2.3 / AB CSE3110 1.5.4/1.6.5
What This Feeds Into本单元的去向
Searching and sorting are foundational to more advanced algorithm study. The linear and binary search algorithms you learned here feed directly into AP CSA and ICS4U, where you implement them in Java. The sorting algorithm comparison (Big-O efficiency analysis) you practiced here matches the content of ICS4U C2.2/C2.3 and CSE3110 1.5.4/1.6.5. The link below points to the AP CSA study guide that continues this topic in Java.查找与排序是更高级算法学习的基础。你在这里学到的线性查找和二分查找算法直接输入 AP CSA 和 ICS4U,在那里用 Java 实现。你在这里练习的排序算法比较(大O效率分析)正对应 ICS4U C2.2/C2.3 和 CSE3110 1.5.4/1.6.5 的内容。以下链接指向用 Java 继续这一主题的 AP CSA 学习指南。
AP follow-on guide.AP 后续指南。
AP CSP Big Idea 3 topic 3.11 (Binary Search) and 3.17 (Algorithmic Efficiency) cover the same binary search and efficiency concepts as this guide. AP CSA Unit 4 covers searching and sorting formally in Java including recursive merge sort: this HS guide is the conceptual prerequisite. ICS4U and CSE3110 students: the Big-O analysis in the Honors going-deeper boxes is written for your level.AP CSP 大概念 3 主题 3.11(二分查找)和 3.17(算法效率)涵盖与本指南相同的二分查找和效率概念。AP CSA Unit 4 在 Java 中正式涵盖查找和排序,包括递归归并排序,本 HS 指南是概念性先修课。ICS4U 和 CSE3110 学生:荣誉深入框中的大O分析正是为你的水平而写。
This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。
Common Questions常见问题
What is the difference between linear search and binary search?线性查找和二分查找有什么区别?
Linear search checks each element one by one and works on any list, taking up to n steps, while binary search repeatedly halves a sorted list and takes only about log base 2 of n steps. Binary search is far faster but requires the list to be sorted first.线性查找逐个检查每个元素,适用于任何列表,最多需要 n 步;二分查找反复将有序列表对半分,只需大约以 2 为底 n 的对数步。二分查找快得多,但要求列表先排好序。
Why is binary search so much faster for large lists?为什么对大列表二分查找快这么多?
Binary search runs in O(log n) time, so doubling the list size adds only one extra step. For one million items linear search may take up to one million steps, but binary search needs at most about 20.二分查找的时间复杂度是 O(log n),所以列表大小翻倍只增加一步。对于一百万个元素,线性查找可能要多达一百万步,而二分查找最多约 20 步。
What is the difference between bubble sort, selection sort, and insertion sort?冒泡排序、选择排序和插入排序有什么区别?
All three are O(n squared) sorts: bubble sort repeatedly swaps adjacent elements so the largest bubbles to the end, selection sort finds the smallest remaining element each pass with at most n-1 swaps, and insertion sort slides each element into place among the already-sorted ones, running in O(n) when the list is nearly sorted.三者都是 O(n 的平方) 的排序:冒泡排序反复交换相邻元素,使最大值冒到末尾;选择排序每趟找出剩余最小元素,最多 n-1 次交换;插入排序把每个元素插入到已排序部分中,列表接近有序时为 O(n)。
Syllabus alignment & how to use this guide大纲对照与使用说明
How to use this guide如何使用本指南
Searching and sorting are grade-12/Advanced-level topics in all four curricula. Ontario places them exclusively in ICS4U (Grade 12). Alberta names them in CSE3110 (Advanced, 3xxx). CSTA puts efficiency evaluation in Level 3B (the specialist elective stream). BC implies them under Computer Programming 12 "Advanced programming structures." All four use the same core algorithms, so this guide is written for any student who reaches this topic regardless of course code. The Honors flag marks content that maps to formal complexity analysis (ICS4U C2, CSE3110 outcome 1.5.4/1.6.5).查找与排序在四套大纲中均为 12 年级或高级水平内容。安大略将其完全置于 ICS4U(12 年级);阿尔伯塔将其列入 CSE3110(高级模块,3xxx 系列);CSTA 将效率评估置于 3B 级(专业选修流);BC 将其隐含于 Computer Programming 12"高级编程结构"之下。四套大纲的核心算法相同,因此本指南适用于任何到达此主题的学生,无论课程代码如何。荣誉标记(Honors)标注正式复杂度分析内容(对应 ICS4U C2 和 CSE3110 结果 1.5.4/1.6.5)。
| If you are in…如果你在… | Focus on these sections重点学习 | Defer / lighter可推迟 / 减负 | Source依据 |
|---|---|---|---|
| 🇺🇸 US CSTA 3B / AP CSP美国 CSTA 3B / AP CSP | §1–§3 core (search + efficiency). AP CSP topic 3.11 covers binary search; topic 3.17 covers efficiency. CSTA 3B-AP-10 (classic algorithms) and 3B-AP-11 (evaluate efficiency) are the specialist standards.§1–§3 核心(查找 + 效率)。AP CSP 主题 3.11 涵盖二分查找;主题 3.17 涵盖效率。CSTA 3B-AP-10(经典算法)和 3B-AP-11(评估效率)是专业标准。 | Sort implementation details (§4–§6) are enrichment for AP CSP; AP CSA (Java) covers them formally.排序实现细节(§4–§6)对 AP CSP 为拓展;AP CSA(Java)正式涵盖它们。 | CSTA K-12 and AP CSP : CSTA 3B-AP-10, 3B-AP-11; AP CSP 3.11, 3.17; AAP-4.A:CSTA 3B-AP-10、3B-AP-11;AP CSP 3.11、3.17;AAP-4.A |
| 🇨🇦 ON Grade 12: ICS4U安大略 12 年级:ICS4U | §1 through §7 in full. ICS4U A3.2 (linear + binary search), A3.4 (bubble, insertion, selection sorts), C2.2 (compare search efficiency), C2.3 (compare sort efficiency) all map directly.§1 至 §7 完整学习。ICS4U A3.2(线性+二分查找)、A3.4(冒泡、插入、选择排序)、C2.2(比较查找效率)、C2.3(比较排序效率)均直接对应。 | Recursion/merge-sort (A3.6) and formal Big-O derivations (C2.3 full) are ICS4U-only going-deeper material: flagged Honors.递归/归并排序(A3.6)和正式大O推导(C2.3 完整)属 ICS4U-only 深入内容,标注荣誉标记。 | ON/BC Computer Studies 11-12 : ICS4U A3.2, A3.4, A3.6, C2.2, C2.3:ICS4U A3.2、A3.4、A3.6、C2.2、C2.3 |
| 🇨🇦 BC: CP12BC: CP12 | §1 through §7. Computer Programming 12 "Advanced programming structures" and "Management of complexity" are the closest BC anchors; no explicit sorting/searching standard exists.§1 至 §7。BC Computer Programming 12"高级编程结构"和"复杂度管理"是最接近的 BC 依据;没有明确的排序/查找标准。 | Formal Big-O analysis is enrichment for BC CP12 students.正式大O分析对 BC CP12 学生为拓展内容。 | ON/BC Computer Studies 11-12 : BC CP12 "Advanced programming structures"; "Management of complexity":BC CP12"高级编程结构";"复杂度管理" |
| 🇨🇦 AB: CSE3110阿尔伯塔:CSE3110 | §1 through §7 in full. CSE3110 outcomes 1.5 (linear + binary search) and 1.6 (bubble, selection, insertion sort) with efficiency comparison (1.5.4, 1.6.5) are a near-perfect match for this guide.§1 至 §7 完整学习。CSE3110 结果 1.5(线性+二分查找)和 1.6(冒泡、选择、插入排序)以及效率比较(1.5.4、1.6.5)与本指南高度契合。 | Recursive sorts (quicksort, merge sort) are CSE3310: outside scope of this guide.递归排序(快速排序、归并排序)属 CSE3310,超出本指南范围。 | Alberta CTS Computing Science : CSE3110 outcomes 1.5.1–1.5.4, 1.6.1–1.6.5:CSE3110 结果 1.5.1–1.5.4、1.6.1–1.6.5 |
Once you have located your row, use the two cards below for the pace at which you should work through the sections.找到所在行后,用下面两张卡片决定推进速度。
Memorise five things: linear search scans one-by-one (worst case n steps); binary search halves each time (worst case ⌊log₂n⌋ + 1 comparisons, sorted list required); bubble sort compares adjacent pairs; selection sort finds the minimum each pass; insertion sort builds a sorted left portion one element at a time. Read every cram-cheat box. Skip the Honors Big-O going-deeper box.背熟五件事:线性查找逐个扫描(最坏 n 步);二分查找每次减半(最坏 ⌊log₂n⌋ + 1 次比较,需已排序);冒泡排序比较相邻元素;选择排序每轮找最小值;插入排序逐一将元素插入有序左段。读每个速记框,跳过荣誉大O深入框。
Trace every algorithm by hand with a concrete 6–8 element list before moving on. Know the pre-condition, worst-case step count, and best-use scenario for every algorithm. AP CSP Big Idea 3 topic 3.17 (efficiency) and Ontario ICS4U C2.2/C2.3 require you to compare algorithms by step count, not just name them. The Honors going-deeper boxes introduce Big-O notation at the formal level named in ICS4U and CSE3110.在继续学习之前,用具体的 6–8 个元素列表手工追踪每个算法。掌握每个算法的前提条件、最坏情况步骤数和最佳使用场景。AP CSP 大概念 3 主题 3.17(效率)和安大略 ICS4U C2.2/C2.3 要求你按步骤数比较算法,而不仅仅是叫出名字。荣誉深入框在 ICS4U 和 CSE3110 所列的正式级别引入大O表示法。