High School Computer Science

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/伪代码,每段后附中文注解。

7 sections7 节内容 US CSTA · AP CSP · ON · BC · ABUS CSTA · AP CSP · ON · BC · AB Python + pseudocode worked examplesPython + 伪代码例题

Linear Search线性查找

Learning objectives学习目标
  • 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 -1 belongs after the loop, not inside it.
  • Decide when linear search is the right tool.
  • 说明线性查找的前提条件(无)以及最好和最坏情况。
  • 追踪线性查找并统计比较次数,包括查找成功和失败两种情况。
  • 用伪代码和 Python 编写线性查找,返回索引或 -1。
  • 解释为什么 return -1 应放在循环之后,而不是循环之内。
  • 判断何时线性查找是合适的工具。
Linear search: scan every item in order until the target is found.线性查找(线性查找),按顺序逐个扫描,直到找到目标。
  • 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(未找到)。
CSE3110 outcome 1.5.1 names "linear search" explicitly. ICS4U A3.2 says "create linear and binary search algorithms to find data in an array." AP CSP topic 3.11 covers binary search, and comparing efficiency needs linear search as the baseline.CSE3110 结果 1.5.1 明确列出"线性查找"。ICS4U A3.2 要求"创建线性和二分查找算法以在数组中查找数据"。AP CSP 主题 3.11 涉及二分查找,比较效率时需要以线性查找作为基准。
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 时才会成功。正确位置是在循环之后,也就是所有元素都检查完毕之后。

A linear search checks a list of 200 items and the target is the very last item. How many comparisons does it make?线性查找检查含 200 个元素的列表,目标恰好是最后一个元素。需要比较多少次?
§1 · Q1
11
100100
200200
88
Linear search checks each item in order. If the target is at the last position (index 199), it must compare all 200 items before finding it. This is the worst case: n comparisons for a list of n items.线性查找按顺序逐个检查。若目标在最后位置(索引 199),则必须比较全部 200 个元素才能找到。这是最坏情况:n 个元素的列表需 n 次比较。
Linear search scans left to right; finding the last item requires checking all n items. Worst case = n comparisons. Binary search would take about log₂(200) ≈ 8 steps (but needs a sorted list).线性查找从左到右扫描;找到最后一项需检查全部 n 个元素。最坏情况 = n 次比较。二分查找约需 log₂(200) ≈ 8 步(但需要已排序列表)。
What does a linear search return when the target is not found in the list?当目标不在列表中时,线性查找返回什么?
§1 · Q2
00
The last index checked最后检查的索引
None / null with no signal无信号地返回 None/null
−1 (a sentinel value meaning “not found”)−1(表示"未找到"的哨兵值)
The conventional return value for "not found" in a search algorithm is −1, because −1 cannot be a valid list index. This is called a sentinel value. Returning 0 would be ambiguous (0 is a valid index). Python's list.index() raises ValueError instead, but the classic algorithm uses −1.查找算法"未找到"的惯用返回值是 −1,因为 −1 不可能是有效列表索引。这称为哨兵值。返回 0 会产生歧义(0 是有效索引)。Python 的 list.index() 改为抛出 ValueError,但经典算法使用 −1。
The standard "not found" sentinel is −1. It cannot be confused with a valid index (all valid indices are ≥ 0).标准"未找到"哨兵是 −1。它不会与有效索引混淆(所有有效索引均 ≥ 0)。
Exam tip考试提示

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 放在循环内,导致遇到第一个不匹配就结束查找。

Check your understanding自我检测
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二分查找

Learning objectives学习目标
  • State the pre-condition for binary search (a sorted list) and explain why it is needed.
  • Trace low, mid and high at 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,并说明它与减半次数的区别。
Binary search: halve the search space on every comparison. Requires a sorted list.二分查找(二分查找),每次比较将搜索范围减半。必须是已排序列表。
  • 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.:将目标与中间元素比较。若目标较小,搜索左半部分;若较大,搜索右半部分;若相等,找到。
CSE3110 outcome 1.5.2 names "binary search." ICS4U A3.2 requires creating it. AP CSP topic 3.11 is "Binary Search."CSE3110 结果 1.5.2 列出"二分查找"。ICS4U A3.2 要求创建它。AP CSP 主题 3.11 即"二分查找"。
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步骤lowhighmiddata[mid]data[mid]Action操作
10942525 < 34 → low = 525 < 34 → low = 5
25975555 > 34 → high = 655 > 34 → high = 6
35653434 == 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 万次。

00 11 22 33 44 55 66 77 88 99 Step 1: low 0, high 9, mid 4. 25 < 34, so low = 5第 1 步:low 0,high 9,mid 4。25 < 34,所以 low = 5 33 88 1212 1717 2525 3434 4141 5555 6868 7777 LL MM HH Step 2: low 5, high 9, mid 7. 55 > 34, so high = 6第 2 步:low 5,high 9,mid 7。55 > 34,所以 high = 6 33 88 1212 1717 2525 3434 4141 5555 6868 7777 LL MM HH Step 3: low 5, high 6, mid 5. 34 = 34, found at index 5第 3 步:low 5,high 6,mid 5。34 = 34,在索引 5 找到 33 88 1212 1717 2525 3434 4141 5555 6868 7777 L,ML,M HH
Figure 1. Binary search for 34 in the sorted list from Worked Example 3. Each row is one step: L, M and H mark 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步骤lowhighmiddata[mid]Action操作
10731414 < 30, so low = 414 < 30, so low = 4
24752727 < 30, so low = 627 < 30, so low = 6
36763333 > 30, so high = 533 > 30, so high = 5
465--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 可能使窗口保持不变,循环永远不会结束。

Which of the following is a requirement for binary search to work correctly?以下哪项是二分查找正确工作的必要条件?
§2 · Q1
The list must contain only integers列表必须只包含整数
The list must have an even number of elements列表必须有偶数个元素
The list must be sorted in ascending order列表必须按升序排列
The target must always be present in the list目标必须一定在列表中
Binary search works by comparing the target to the middle element and eliminating half the list. This only works if the list is sorted: without ordering, "search the left half" has no meaning. CSE3110 outcome 1.5.4 explicitly requires comparing the "data structures required" for linear vs binary search: the sorted precondition is the key difference.二分查找通过将目标与中间元素比较并淘汰一半列表来工作。只有在列表已排序时才有效,没有顺序,"搜索左半部分"毫无意义。CSE3110 结果 1.5.4 明确要求比较线性与二分查找所需的"数据结构",已排序前提条件是关键区别。
Binary search requires a sorted list. It works on any comparable type (not just integers), any list length, and correctly returns −1 if the target is absent.二分查找需要已排序列表。它适用于任何可比较类型(不仅仅是整数),任何列表长度,目标不存在时正确返回 −1。
A sorted list has 1,024 items. How many comparisons does binary search need in the worst case?一个已排序列表有 1024 个元素。二分查找在最坏情况下需要多少次比较?
§2 · Q2
512
11
1024
100
Binary search halves the search space each step. Starting from 1,024: 1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4 → 2 → 1. That is 10 halvings, and one last comparison is still needed on the single item left, so 10 + 1 = 11 comparisons. This is ⌊log₂(1024)⌋ + 1, where log₂(1024) = 10 because 2¹⁰ = 1024.二分查找每步将搜索空间减半。从 1024 开始:1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4 → 2 → 1。共 10 次减半,剩下的最后一个元素还要再比较一次,所以是 10 + 1 = 11 次比较,即 ⌊log₂(1024)⌋ + 1,其中 log₂(1024) = 10,因为 2¹⁰ = 1024。
In the worst case binary search makes ⌊log₂(n)⌋ + 1 comparisons. log₂(1024) = 10 halvings, so 10 + 1 = 11 comparisons.二分查找最坏情况需 ⌊log₂(n)⌋ + 1 次比较。log₂(1024) = 10 次减半,所以是 10 + 1 = 11 次比较。
Exam tip考试提示

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。

Check your understanding自我检测
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概念)

Learning objectives学习目标
  • 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 时线性查找和二分查找的最坏情况步骤数,并说明使用哪种计数。
  • 通过比较总代价,判断先排序是否划算。
Count steps to compare algorithms: more steps = slower.计步比较算法,步骤越多越慢。
  • 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) 显著更优。
AP CSP topic 3.17 (AAP-4.A) and ICS4U C2.2/C2.3 require comparing efficiency. CSE3110 outcomes 1.5.4 and 1.6.5 require "compare and contrast the computational efficiencies." CSTA 3B-AP-11 says "Evaluate algorithms in terms of their efficiency." All four curricula name this.AP CSP 主题 3.17(AAP-4.A)和 ICS4U C2.2/C2.3 要求比较效率。CSE3110 结果 1.5.4 和 1.6.5 要求"比较计算效率"。CSTA 3B-AP-11 要求"从效率方面评估算法"。四套大纲均列出此内容。
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,分别计算线性查找和二分查找的最坏情况步骤数。

nLinear (worst case)线性(最坏)Binary (worst case, comparisons)二分(最坏,比较次数)Ratio比值
8842×
161653.2×
646479.1×
1,0241,0241193.1×
1,000,0001,000,0002050,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 节)。

An algorithm takes about 100 steps for a list of 1,000 items. If the list doubles to 2,000 items and the algorithm needs about one extra step, what growth pattern does this suggest?一个算法在 1000 个元素的列表上约需 100 步。若列表翻倍到 2000 个元素,算法只多需约一步,这说明什么增长模式?
§3 · Q1
Linear growth: O(n)线性增长:O(n)
Logarithmic growth: O(log n)对数增长:O(log n)
Quadratic growth: O(n²)二次增长:O(n²)
Constant growth: O(1)常数增长:O(1)
When doubling the input size adds only about one extra step, that matches logarithmic growth: log₂(1000) ≈ 10 → log₂(2000) ≈ 11. Binary search exhibits exactly this pattern: O(log n).当输入大小翻倍只增加约一步时,符合对数增长:log₂(1000) ≈ 10 → log₂(2000) ≈ 11。二分查找正好表现这种模式,O(log n)。
Linear: doubling n doubles the steps. Logarithmic: doubling n adds only one step. Quadratic: doubling n quadruples the steps. One extra step when n doubles = O(log n).线性:n 翻倍则步骤翻倍。对数:n 翻倍只多一步。二次:n 翻倍则步骤变为四倍。n 翻倍只多一步 = O(log n)。
Why can't you use binary search on the unsorted list [7, 2, 9, 1, 5]?为什么不能对未排序列表 [7, 2, 9, 1, 5] 使用二分查找?
§3 · Q2
The mid-element comparison can eliminate the wrong half, giving an incorrect result中间元素比较可能淘汰错误的一半,导致结果错误
Binary search only works on lists with an even number of elements二分查找只适用于元素数量为偶数的列表
Binary search runs out of memory on unsorted data二分查找在未排序数据上会耗尽内存
Binary search can only be implemented in Java, not Python二分查找只能用 Java 实现,不能用 Python
Binary search works by deciding "target must be in the left half" or "target must be in the right half" based on the mid-element. This is only valid if the list is sorted: on [7,2,9,1,5], the mid element is 9, but that does not tell you which half contains 2. You would eliminate the wrong half and miss the answer.二分查找通过判断"目标一定在左半"或"目标一定在右半"来运作,这只在列表已排序时才成立。对于 [7,2,9,1,5],中间元素是 9,但这无法告知哪半包含 2;你会淘汰错误的一半而错过答案。
The sorted-list requirement is the key constraint. Binary search works on any length, any language. The issue is correctness, not memory or language.已排序列表的要求是关键约束。二分查找适用于任意长度、任何语言。问题在于正确性,而非内存或语言。
Exam tip考试提示

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) 更好而不提可能需要先排序,以及在同一张表里混用比较次数和减半次数。

Check your understanding自我检测
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冒泡排序

Learning objectives学习目标
  • 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 编写冒泡排序及其提前退出版本。
Bubble sort: compare adjacent pairs; swap if out of order; repeat until no swaps occur.冒泡排序(冒泡排序),比较相邻元素;如果顺序错误则交换;重复直到无交换。
  • 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, a swaps two variables. No temporary variable needed.:a, b = b, a 交换两个变量,无需临时变量。
CSE3110 outcome 1.6.1 names "exchange sort; e.g., bubble sort" explicitly. ICS4U A3.4 says "create a sort algorithm (e.g., bubble, insertion, selection)." Bubble sort is the canonical teaching example because its logic is easy to trace by hand.CSE3110 结果 1.6.1 明确列出"交换排序,如冒泡排序"。ICS4U A3.4 要求"创建排序算法(如冒泡、插入、选择排序)"。冒泡排序是典型的教学示例,因为其逻辑易于手工追踪。
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 交换两个元素的惯用写法。

Start初始 55 33 88 11 44 Pass 1第 1 遍 33 55 11 44 88 3 swaps3 次交换 Pass 2第 2 遍 33 11 44 55 88 2 swaps2 次交换 Pass 3第 3 遍 11 33 44 55 88 1 swap1 次交换 Pass 4第 4 遍 11 33 44 55 88 0 swaps0 次交换
Figure 2. Bubble sort on [5, 3, 8, 1, 4], matching Worked Example 7: one row per pass. Shaded cells are in their final position (after pass k, the k largest). The swap counts 3, 2, 1, 0 add up to the 6 swaps in the table.图 2. 对 [5, 3, 8, 1, 4] 做冒泡排序,与例题 7 一致:每遍一行。阴影单元格已在最终位置(第 k 遍后是最大的 k 个元素)。交换次数 3、2、1、0 之和为表中的 6 次交换。
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]712
[1, 2, 3, 4, 5]401
[5, 4, 3, 2, 1]10104

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 次交换。

After one complete pass of bubble sort on [4, 2, 7, 1, 6], which element is guaranteed to be in its final sorted position?对 [4, 2, 7, 1, 6] 完成一次完整的冒泡排序遍历后,哪个元素一定处于最终排序位置?
§4 · Q1
7 (the largest element, now at the right end)7(最大元素,已移至最右端)
4 (the first element)4(第一个元素)
1 (the smallest element)1(最小元素)
6 (the second largest)6(第二大元素)
After one pass of bubble sort, the largest element has bubbled all the way to the rightmost position and is in its final sorted location. This is why it's called "bubble" sort: the maximum "floats up" to the top (right end) in each pass.一次冒泡排序遍历后,最大元素已完全冒泡到最右端,处于其最终排序位置。这就是"冒泡"排序名称的由来,每遍中最大值"浮"到顶部(右端)。
Bubble sort moves the largest unsorted element to the right end on each pass. After pass 1, the maximum (7) is at index 4 and is done. After pass 2, the second-largest is done. And so on.冒泡排序每遍将最大的未排序元素移至右端。第 1 遍后,最大值(7)在索引 4 处,已完成。第 2 遍后,第二大值完成。以此类推。
Bubble sort has a worst-case of O(n²) comparisons. For n = 10, the maximum number of comparisons is approximately:冒泡排序最坏情况为 O(n²) 次比较。对于 n = 10,最多比较次数约为:
§4 · Q2
10
20
45
100
Bubble sort makes (n-1) + (n-2) + ... + 1 = n(n-1)/2 comparisons in the worst case. For n=10: 10×9/2 = 45. This is O(n²) growth, and for n=100 it would be 4,950 comparisons.冒泡排序最坏情况下比较次数为 (n-1) + (n-2) + ... + 1 = n(n-1)/2。n=10 时:10×9/2 = 45。这是 O(n²) 增长,n=100 时将需要 4950 次比较。
Bubble sort worst case = n(n-1)/2 comparisons. For n=10: 9+8+7+6+5+4+3+2+1 = 45. This is O(n²).冒泡排序最坏情况 = n(n-1)/2 次比较。n=10 时:9+8+7+6+5+4+3+2+1 = 45。这是 O(n²)。
Exam tip考试提示

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);只有带提前退出的版本才是。

Check your understanding自我检测
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选择排序

Learning objectives学习目标
  • 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 次交换。
  • 解释交换次数较少在什么情况下重要。
Selection sort: on each pass, find the minimum of the unsorted portion and place it at the front.选择排序(选择排序),每遍找出未排序部分的最小值,放到前面。
  • 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 个元素处于最终排序位置。
CSE3110 outcome 1.6.2 names "selection sort" explicitly. ICS4U A3.4 includes selection sort. Selection sort is less stable than insertion sort but makes fewer writes to memory.CSE3110 结果 1.6.2 明确列出"选择排序"。ICS4U A3.4 包含选择排序。选择排序的稳定性不如插入排序,但对内存的写入次数更少。
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 次。

After 3 passes of selection sort on a list of 8 elements, how many elements are guaranteed to be in their final sorted positions?对 8 个元素的列表进行 3 遍选择排序后,有多少个元素一定处于最终排序位置?
§5 · Q1
1
2
4
3
Selection sort places exactly one element in its final position per pass. After 3 passes, the 3 smallest elements are at indices 0, 1, and 2, and will not move again. In general: after k passes, the first k elements are fully sorted.选择排序每遍将恰好一个元素放到最终位置。3 遍后,3 个最小元素位于索引 0、1、2,不会再移动。一般规律:k 遍后,前 k 个元素完全排好。
Selection sort: one element finalized per pass. After 3 passes = 3 elements in final positions (the 3 smallest).选择排序:每遍最终确定一个元素。3 遍后 = 3 个元素处于最终位置(最小的 3 个)。
Compared to bubble sort, selection sort makes fewer swaps but the same number of comparisons (O(n²) both). What is the practical advantage of fewer swaps?与冒泡排序相比,选择排序的交换次数更少,但比较次数相同(均为 O(n²))。更少交换的实际优势是什么?
§5 · Q2
Fewer writes to memory, which matters when write operations are expensive (e.g., flash storage)减少内存写入次数,当写入操作代价高昂时(如闪存)这很重要
It makes selection sort faster for every type of data使选择排序对所有类型的数据都更快
It reduces the number of comparisons to O(n)将比较次数减少到 O(n)
It makes selection sort stable使选择排序稳定
Fewer swaps means fewer write operations. On hardware where writes are significantly more expensive than reads (e.g., EEPROM, flash storage, or when data records are large), selection sort's n-1 swaps are preferable to bubble sort's many more swaps. Both are O(n²) for comparisons.更少交换意味着更少写入操作。在写入远比读取昂贵的硬件上(如 EEPROM、闪存,或数据记录较大时),选择排序的 n-1 次交换优于冒泡排序更多次的交换。两者比较次数均为 O(n²)。
Selection sort still has O(n²) comparisons: it is not generally faster in terms of comparisons. The advantage is specifically in write operations. It is also not stable by default.选择排序比较次数仍为 O(n²),在比较方面并不普遍更快。优势具体在于写入操作。默认情况下也不稳定。
Exam tip考试提示

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 次。常见错误:以为选择排序在已排序输入上会更快(不会),以及说它是稳定的(一般不是)。

Check your understanding自我检测
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插入排序

Learning objectives学习目标
  • 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)。
  • 解释为什么插入排序适合接近有序的数据。
Insertion sort: build a sorted left portion one element at a time, inserting each new element in the correct position.插入排序(插入排序),每次将一个新元素插入正确位置,逐步构建左侧有序部分。
  • 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²),当列表完全逆序时(每个元素都需一路向左移位)。
CSE3110 outcome 1.6.3 names "insertion sort" explicitly. ICS4U A3.4 includes it. Insertion sort is the most efficient of the three simple sorts for nearly-sorted data and is used internally by Python's built-in sort for small sub-arrays.CSE3110 结果 1.6.3 明确列出"插入排序"。ICS4U A3.4 包含它。插入排序对近乎有序数据是三种简单排序中最高效的,Python 内置排序在小子数组上内部使用插入排序。
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.逐步追踪。

ikeyList after insertion插入后列表
Start初始–[5, 3, 8, 1, 4]
13[3, 5, 8, 1, 4]
28[3, 5, 8, 1, 4]
31[1, 3, 5, 8, 4]
44[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]40
[2, 4, 1, 6, 8]52
[5, 4, 3, 2, 1]1010

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²) 的最坏情况。

In insertion sort, what happens to elements that are larger than the key being inserted?在插入排序中,比待插入的 key 大的元素会发生什么?
§6 · Q1
They are swapped with the key immediately立即与 key 交换
They are shifted one position to the right to make room for the key向右移一位,为 key 腾出空间
They are moved to the end of the list移到列表末尾
They are deleted and re-inserted later被删除,稍后重新插入
Insertion sort shifts elements one position right (not swaps) to create an empty slot for the key. This is more efficient than swapping because a shift is one write operation while a swap requires three. The key is then placed in the vacated slot.插入排序将元素向右移一位(而非交换)以为 key 创建空槽。这比交换更高效,因为移位是一次写入操作,而交换需要三次。然后将 key 放入腾出的槽中。
Insertion sort uses shifts (not swaps). Each element larger than the key moves right by one position; the key then drops into the gap left behind.插入排序使用移位(不是交换)。每个比 key 大的元素向右移一位;key 随后放入留下的间隙。
For which type of input is insertion sort most efficient (approaching O(n))?对于哪种类型的输入,插入排序最高效(趋近于 O(n))?
§6 · Q2
A list in reverse order完全逆序的列表
A randomly shuffled list随机打乱的列表
A list that is already sorted or nearly sorted已排序或近乎有序的列表
A list that alternates large and small values (9, 1, 8, 2, 7, 3, ...)大小值交替的列表(9, 1, 8, 2, 7, 3, ...)
When the list is already sorted, each element's key is greater than or equal to all preceding elements, so the WHILE loop terminates immediately for each i: just one comparison per element, giving O(n) total. A nearly-sorted list has very few shifts needed. This O(n) best-case is insertion sort's key advantage over bubble and selection sort.当列表已排好时,每个元素的 key 都大于等于前面所有元素,因此每个 i 的 WHILE 循环立即终止,每个元素只需一次比较,总计 O(n)。近乎有序的列表只需极少移位。这种 O(n) 最好情况是插入排序相对于冒泡排序和选择排序的关键优势。
Reverse order is the worst case for insertion sort (O(n²) shifts). A sorted list is the best case because no element needs to shift left at all.逆序是插入排序的最坏情况(O(n²) 次移位)。已排序列表是最好情况,因为没有元素需要向左移位。
Exam tip考试提示

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。

Check your understanding自我检测
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排序比较与内置排序

Learning objectives学习目标
  • Compare linear search, binary search and the three simple sorts by pre-condition, best case and worst case.
  • Use sorted() and .sort() correctly, including reverse, key and the None returned 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 summary: memorise this table.算法摘要,背熟这张表。
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近乎有序数据最佳
CSE3110 outcome 1.6.5 and ICS4U C2.3 both require "comparing and contrasting computational efficiencies of different classes of sorts." The table above is your answer framework.CSE3110 结果 1.6.5 和 ICS4U C2.3 均要求"比较不同类别排序的计算效率"。上表即你的答题框架。
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。

You have a list of 10,000 student names already sorted alphabetically. You need to search it 500 times. What is the most efficient approach?你有一个按字母顺序排好的 10000 名学生姓名列表,需要查找 500 次。最高效的方法是什么?
§7 · Q1
Sort the list again before each search using bubble sort每次查找前用冒泡排序重新排序
Use linear search each time because the list is small enough每次使用线性查找,因为列表够小
Sort the list with insertion sort then use linear search用插入排序排序,再使用线性查找
Use binary search directly (list is already sorted) for all 500 searches直接使用二分查找(列表已排好)进行全部 500 次查找
The list is already sorted, so binary search applies immediately. Each search takes at most log₂(10,000) ≈ 14 comparisons. Total: 500 × 14 = 7,000 comparisons. Linear search would take 500 × 10,000 = 5,000,000 comparisons in the worst case. Binary search wins by over 700×.列表已排好,二分查找可直接使用。每次查找最多 log₂(10,000) ≈ 14 次比较。总计:500 × 14 = 7,000 次比较。线性查找最坏情况:500 × 10,000 = 500 万次比较。二分查找胜出 700 余倍。
The list is already sorted: no re-sorting needed. Binary search requires O(log n) per lookup, far cheaper than O(n) linear search for 500 queries on 10,000 items.列表已排好,无需重新排序。二分查找每次查找 O(log n),远比 10000 个元素 500 次查询的 O(n) 线性查找便宜。
In Python, what is the difference between sorted(data) and data.sort()?在 Python 中,sorted(data) 和 data.sort() 有什么区别?
§7 · Q2
sorted() is faster; .sort() is slowersorted() 更快;.sort() 更慢
They are identical in all respects在所有方面完全相同
sorted() returns a new list and leaves the original unchanged; .sort() modifies the original list in place and returns Nonesorted() 返回新列表,原列表不变;.sort() 原地修改原列表并返回 None
sorted() only works on strings; .sort() only works on numberssorted() 只适用于字符串;.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()。
Speed is the same (both use Timsort). The key difference is in-place vs new-list. Both work on any comparable type.速度相同(均使用 Timsort)。关键区别是原地修改还是返回新列表。两者均适用于任何可比较类型。
Exam tip考试提示

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 的结果做索引。

Check your understanding自我检测
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考试策略与常见陷阱

Before answering any algorithm question回答任何算法问题前
  • 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(时间复杂度)。
Search questions (§1-§2)查找问题(§1-§2)
  • 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 的值。追踪题切勿跳步。
Sort questions (§4-§6)排序问题(§4-§6)
  • 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 明确列出此比较。
Answer hygiene作答规范
  • 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, use DISPLAY(). 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闪卡

0 / 14 flipped0 / 14 已翻
Linear search线性查找
Scan every item in order. Worst case: n steps. No pre-condition. Returns −1 if not found.按顺序逐个扫描。最坏情况:n 步。无前提条件。未找到返回 −1。
Binary search二分查找
Halve the search space each step. Worst case: ⌊log₂(n)⌋ + 1 comparisons. Pre-condition: sorted list. 1024 items → 11 comparisons.每步将搜索空间减半。最坏情况:⌊log₂(n)⌋ + 1 次比较。前提:已排序列表。1024 个元素 → 11 次比较。
Why does binary search need a sorted list?二分查找为何需要有序列表?
It eliminates half the list based on whether target is less or greater than mid. Without ordering, this elimination is invalid.它根据目标是否小于/大于中间值来淘汰一半列表。无顺序时淘汰无效。
O(n) vs O(log n)O(n) 与 O(log n)
O(n): linear growth, so doubling n doubles the steps. O(log n): logarithmic growth, so doubling n adds only 1 step. For 1M items: 1,000,000 vs 20 steps.O(n):线性增长,所以 n 翻倍则步骤翻倍。O(log n):对数增长,所以 n 翻倍只多 1 步。100 万元素:100 万步 vs 20 步。
Bubble sort冒泡排序
Compare adjacent pairs; swap if out of order. Each pass bubbles the largest unsorted element to the right. O(n²) worst case.比较相邻元素;顺序错误则交换。每遍将最大未排序元素冒泡到右端。最坏情况 O(n²)。
Selection sort选择排序
Find minimum of unsorted portion; swap it to the front. At most n−1 swaps. O(n²) comparisons always (no early exit).找未排序部分最小值;交换到前面。最多 n−1 次交换。比较始终 O(n²)(无提前退出)。
Insertion sort插入排序
Build sorted left portion one element at a time; shift larger elements right. Best case O(n) on sorted data; worst case O(n²).每次将一个元素插入有序左段,将较大元素右移。已排序数据最好情况 O(n);最坏 O(n²)。
Which sort has the best best-case?哪种排序的最好情况最优?
Insertion sort: O(n) when already sorted (no shifts needed). Selection sort is always O(n²). Bubble sort O(n) only with early-exit optimisation.插入排序:已排序时 O(n)(无需移位)。选择排序始终 O(n²)。冒泡排序仅在带提前退出优化时为 O(n)。
sorted() vs .sort()sorted() 与 .sort()
sorted(data) returns a new sorted list; original unchanged. data.sort() modifies original in place; returns None.sorted(data) 返回新排序列表;原列表不变。data.sort() 原地修改原列表;返回 None。
Time complexity of Python's built-in sort?Python 内置排序的时间复杂度?
O(n log n) worst case (Timsort). Much better than O(n²) for large n. Always prefer it over manual bubble/selection/insertion sort in production.最坏情况 O(n log n)(Timsort)。对大 n 远优于 O(n²)。实际项目中始终优先使用它,而非手动实现的冒泡/选择/插入排序。
Algorithm efficiency算法效率
How an algorithm's resource use (steps / time) grows with input size n. Compare using step counts or Big-O. CSTA 3B-AP-11; AP CSP 3.17; ICS4U C2; CSE3110 1.5.4.算法资源使用(步骤/时间)随输入大小 n 增长的方式。用步骤数或大O比较。CSTA 3B-AP-11;AP CSP 3.17;ICS4U C2;CSE3110 1.5.4。
log₂(1024) = ?log₂(1024) = ?
10. Because 2¹⁰ = 1024. Binary search on 1024 items halves the list 10 times and makes at most 11 comparisons.10。因为 2¹⁰ = 1024。对 1024 个元素进行二分查找,列表被减半 10 次,最多需要 11 次比较。
Bubble sort: after k passes, what is guaranteed?冒泡排序:k 遍后保证什么?
The k largest elements are in their final positions at the right end of the list.最大的 k 个元素处于列表右端的最终位置。
Selection sort: after k passes, what is guaranteed?选择排序:k 遍后保证什么?
The k smallest elements are in their final sorted positions at the left end of the list.最小的 k 个元素处于列表左端的最终排序位置。

Practice Quiz综合测验

Linear search on an unsorted list of 500 items. The target is not present. How many comparisons are made?对含 500 个元素的未排序列表进行线性查找,目标不存在。需要多少次比较?
Q1
1
9
250
500
When the target is not present, linear search must check every single item before concluding it is absent. 500 items = 500 comparisons. This is the definition of O(n) worst case.目标不存在时,线性查找必须检查每一个元素才能确认不存在。500 个元素 = 500 次比较。这就是 O(n) 最坏情况的定义。
Linear search worst case = n comparisons when target is absent. All 500 must be checked.线性查找最坏情况:目标不存在时需 n 次比较,全部 500 个都需检查。
Sorted list: [1, 5, 9, 12, 18, 24, 30]. Binary search for target = 9. What is the first mid element checked?有序列表:[1, 5, 9, 12, 18, 24, 30]。对目标 9 进行二分查找。第一个检查的中间元素是什么?
Q2
1
9
12
18
List has 7 elements (indices 0–6). mid = (0+6)//2 = 3. list[3] = 12. Since 9 < 12, we search the left half [0..2] next. Total: 3 comparisons to find 9 (mid 3 gives 12, mid 1 gives 5, mid 2 gives 9).列表有 7 个元素(索引 0–6)。mid = (0+6)//2 = 3。list[3] = 12。因为 9 < 12,下一步搜索左半部分 [0..2]。共 3 次比较找到 9(mid 3 得 12,mid 1 得 5,mid 2 得 9)。
Binary search starts at mid = (low+high)//2 = (0+6)//2 = 3. list[3] = 12. Not 9 yet, so go left.二分查找从 mid = (low+high)//2 = (0+6)//2 = 3 开始。list[3] = 12。还不是 9,所以向左搜索。
One complete pass of bubble sort on [3, 1, 4, 1, 5]. What is the list after the pass?对 [3, 1, 4, 1, 5] 进行一次完整冒泡排序遍历后,列表是什么?
Q3
[1, 3, 1, 4, 5]
[1, 1, 3, 4, 5]
[3, 1, 1, 4, 5]
[1, 3, 4, 1, 5]
Pass: compare (3,1)→swap [1,3,4,1,5]; (3,4) no swap; (4,1)→swap [1,3,1,4,5]; (4,5) no swap. Result: [1,3,1,4,5]. The largest element (5) is now at the right end.遍历:比较 (3,1) → 交换 [1,3,4,1,5];(3,4) 不交换;(4,1) → 交换 [1,3,1,4,5];(4,5) 不交换。结果:[1,3,1,4,5]。最大元素(5)现在在右端。
Bubble sort trace: (3,1) swap → [1,3,4,1,5]; (3,4) no swap; (4,1) swap → [1,3,1,4,5]; (4,5) no swap. One pass puts 5 at the end.冒泡排序追踪:(3,1) 交换 → [1,3,4,1,5];(3,4) 不交换;(4,1) 交换 → [1,3,1,4,5];(4,5) 不交换。一遍将 5 移至末尾。
Which sort algorithm has O(n) best case and O(n²) worst case, making it ideal for nearly-sorted data?哪种排序算法最好情况为 O(n)、最坏情况为 O(n²),使其适合近乎有序的数据?
Q4
Selection sort选择排序
Insertion sort插入排序
Bubble sort without early exit无提前退出的冒泡排序
Linear search线性查找
Insertion sort has O(n) best case when the list is already sorted (zero shifts per element) and O(n²) worst case when reversed. This makes it optimal for nearly-sorted data. Selection sort is always O(n²), so it never benefits from existing order.插入排序最好情况为 O(n)(列表已排序时每个元素零移位),最坏情况为 O(n²)(逆序时)。这使其在近乎有序数据上最优。选择排序始终为 O(n²),所以从不受益于现有顺序。
Insertion sort: best O(n), worst O(n²). Selection sort: always O(n²). These are core facts for ICS4U C2.3 and CSE3110 outcome 1.6.5.插入排序:最好 O(n),最坏 O(n²)。选择排序:始终 O(n²)。这是 ICS4U C2.3 和 CSE3110 结果 1.6.5 的核心知识点。
Which CSTA standard says "Evaluate algorithms in terms of their efficiency, correctness, and clarity" (with searching and sorting as example applications)? 🇺🇸 CSTA哪个 CSTA 标准说"从效率、正确性和清晰度方面评估算法"(以查找和排序为示例应用)?🇺🇸 CSTA
Q5
3B-AP-11
3A-AP-13
3B-AP-10
3A-AP-17
CSTA 3B-AP-11 (verbatim): "Evaluate algorithms in terms of their efficiency, correctness, and clarity." The Descriptive Statement explicitly names sorting and searching as examples. 3B-AP-10 is about using classic algorithms; 3B-AP-11 is about evaluating their efficiency.CSTA 3B-AP-11(原文):"从效率、正确性和清晰度方面评估算法。"描述陈述明确将排序和查找列为示例。3B-AP-10 关于使用经典算法;3B-AP-11 关于评估其效率。
3B-AP-11 = evaluate efficiency (with sorting/searching examples). 3B-AP-10 = use and adapt classic algorithms. 3A-AP-13 = create prototypes using algorithms. 3A-AP-17 = decompose problems.3B-AP-11 = 评估效率(以排序/查找为示例)。3B-AP-10 = 使用和调整经典算法。3A-AP-13 = 创建使用算法的原型。3A-AP-17 = 分解问题。
In Ontario ICS4U, which expectation requires creating both linear and binary search algorithms? 🇨🇦 ON在安大略 ICS4U 中,哪项期望要求创建线性和二分查找算法?🇨🇦 ON
Q6
ICS3U B3.1
ICS4U C2.3
ICS4U A3.2
ICS4U A3.4
ICS4U A3.2 (verbatim): "create linear and binary search algorithms to find data in an array." A3.4 is for sort algorithms. C2.2 is for comparing search efficiency. B3.1 is ICS3U, not ICS4U.ICS4U A3.2(原文):"创建线性和二分查找算法以在数组中查找数据。"A3.4 用于排序算法。C2.2 用于比较查找效率。B3.1 是 ICS3U,非 ICS4U。
ICS4U A3.2 = create search algorithms. A3.4 = create sort algorithms. C2.2 = compare search efficiency. C2.3 = compare sort efficiency.ICS4U A3.2 = 创建查找算法。A3.4 = 创建排序算法。C2.2 = 比较查找效率。C2.3 = 比较排序效率。
You sort a list of 10,000 items once with Python's built-in sort. You then do 200 binary searches on it. What is the total complexity class for all operations combined?你用 Python 内置排序对 10000 个元素的列表排序一次,然后进行 200 次二分查找。所有操作合并后的总复杂度类别是什么?
Q7
O(n²) because sorting dominatesO(n²),因为排序占主导
O(n log n) for sorting + O(k log n) for k searches: much better than O(kn) for repeated linear search排序 O(n log n) + k 次查找 O(k log n),远优于重复线性查找的 O(kn)
O(1) because Python is very fastO(1),因为 Python 非常快
O(n² + k) for sort + searches排序加查找 O(n² + k)
Python's built-in sort is O(n log n). Each binary search is O(log n). 200 binary searches = O(200 log n) = O(k log n). Total: O(n log n + k log n). Compare: repeated linear search = O(kn) = 200 × 10,000 = 2,000,000 ops. Sort + binary = roughly 133,000 + 2,800 = 135,800 ops. Roughly a 15× speedup.Python 内置排序为 O(n log n)。每次二分查找为 O(log n)。200 次二分查找 = O(200 log n) = O(k log n)。总计:O(n log n + k log n)。对比:重复线性查找 = O(kn) = 200 × 10,000 = 200 万次操作。排序 + 二分 ≈ 13.3 万 + 2800 = 13.58 万次操作。约 15 倍加速。
Python's built-in sort uses Timsort: O(n log n). Then binary search is O(log n) per query. The combination is O(n log n + k log n), far cheaper than k linear searches at O(kn).Python 内置排序使用 Timsort:O(n log n)。然后每次查询的二分查找为 O(log n)。组合为 O(n log n + k log n),远低于 k 次线性查找的 O(kn)。

Readiness Checklist准备就绪清单

Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。

0 / 11 mastered已掌握 0 / 11

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 CSA Unit 4 · Data Collections (Java: section 4.14 Searching Algorithms + section 4.15 Sorting Algorithms implement and extend exactly the algorithms in this guide using Java arrays and ArrayLists)AP CSA Unit 4 · 数据集合(Java:第 4.14 节查找算法 + 第 4.15 节排序算法使用 Java 数组和 ArrayList 实现并扩展本指南中的算法)

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.找到所在行后,用下面两张卡片决定推进速度。

!
If you are cramming the night before如果你在临阵磨枪

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深入框。

*
If you are going for the top mark如果你目标顶分

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表示法。

Grade-level note.年级说明。 This is a Grade-12 / Advanced-level topic in all four curricula. If you are in an ICS3U, CSE1110, or AP CSP foundations course, this guide is preview material. The Honors chip marks formal Big-O efficiency analysis (ICS4U C2, CSE3110 outcome 1.5.4/1.6.5). Floor students need only the conceptual step-count comparison in the cram boxes.本单元在四套大纲中均为 12 年级/高级水平内容。如果你在 ICS3U、CSE1110 或 AP CSP 基础课程中,本指南为预习材料。Honors 标记正式大O效率分析(ICS4U C2、CSE3110 结果 1.5.4/1.6.5)。基础学生只需掌握速记框中的直观步骤数比较。