跳到主要内容

数据集合

AP 计算机科学 A · 第 4 主题

训练
讲义 词汇表
4.1

数据采集的伦理与社会问题

大纲
Learning ObjectiveEssential Knowledge

4.1.A
Explain the risks to privacy from collecting and storing personal data on computer systems.

  • 4.1.A.1 When using a computer, personal privacy is at risk. When developing new programs, programmers should attempt to safeguard the personal privacy of the user.

4.1.B
Explain the importance of recognizing data quality and potential issues when using a data set.

  • 4.1.B.1 Algorithmic bias describes systemic and repeated errors in a program that create unfair outcomes for a specific group of users.
  • 4.1.B.2 Programmers should be aware of the data set collection method and the potential for bias when using this method before using the data to extrapolate new information or drawing conclusions.
  • 4.1.B.3 Some data sets are incomplete or contain inaccurate data. Using such data in the development or use of a program can cause the program to work incorrectly or inefficiently.

4.1.C
Identify an appropriate data set to use in order to solve a problem or answer a specific question.

  • 4.1.C.1 Contents of a data set might be related to a specific question or topic and might not be appropriate to give correct answers or extrapolate information for a different question or topic.

来源:美国大学理事会 AP 课程与考试说明

收集数据的程序提出隐私(privacy)和同意(consent)的问题。只收集需要的、保护它,并对它的使用诚实。数据能携带偏见(bias),若它不公平地代表每个人,导致不公平的结果——一个随着存储信息而来的责任。

词汇表 训练
英文 中文 拼音
privacy 隐私 yǐn sī
consent 同意 tóng yì
bias 偏见 piān jiàn
4.2

使用数据集导论

大纲
Learning ObjectiveEssential Knowledge

4.2.A
Represent patterns and algorithms that involve data sets found in everyday life using written language or diagrams.

  • 4.2.A.1 A data set is a collection of specific pieces of information or data.
  • 4.2.A.2 Data sets can be manipulated and analyzed to solve a problem or answer a question. When analyzing data sets, values within the set are accessed and utilized one at a time and then processed according to the desired outcome.
  • 4.2.A.3 Data can be represented in a diagram by using a chart or table. This visual can be used to plan the algorithm that will be used to manipulate the data.

来源:美国大学理事会 AP 课程与考试说明

一个单一的变量持有一个值;真实的问题需要存储许多相关的值——一个班级名册、像素、传感器读数。一个数据结构(data structure)组织一个搜集,以便我们能高效地存储、找到和处理项。AP 课程用三个:数组(array)、ArrayList,和 2D 数组

词汇表 训练
英文 中文 拼音
data structure 数据结构 shù jù jié gòu
array 数组 shù zǔ
4.3

数组的创建与访问

大纲
Learning ObjectiveEssential Knowledge

4.3.A
Develop code used to represent collections of related data using one-dimensional (1D) array objects.

  • 4.3.A.1 An array stores multiple values of the same type. The values can be either primitive values or object references.
  • 4.3.A.2 The length of an array is established at the time of creation and cannot be changed. The length of an array can be accessed through the length attribute.
  • 4.3.A.3 When an array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
  • 4.3.A.4 Initializer lists can be used to create and initialize arrays.
  • 4.3.A.5 Square brackets [ ] are used to access and modify an element in a 1D array using an index.
  • 4.3.A.6 The valid index values for an array are 0 through one less than the length of the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException.

来源:美国大学理事会 AP 课程与考试说明

一个数组(array)是一个固定大小的、有序的相同类型值的搜集。索引从 0length - 1:

一个一维数组(一个列表),带它的索引和边界
一个一维数组(一个列表),带它的索引和边界
int[] nums = new int[5];        // five zeros
int[] vals = {3, 1, 4, 1, 5};   // initialized
int first = vals[0];            // 3
int n = vals.length;            // 5 (a field, not a method)

访问 0..length-1 之外的一个索引抛出一个 ArrayIndexOutOfBoundsException

4.4

数组遍历

大纲
Learning ObjectiveEssential Knowledge

4.4.A
Develop code used to traverse the elements in a 1D array and determine the result of these traversals.

  • 4.4.A.1 Traversing an array is when repetition statements are used to access all or an ordered sequence of elements in an array.
  • 4.4.A.2 Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
  • 4.4.A.3 An enhanced for loop header includes a variable, referred to as the enhanced for loop variable. For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
  • 4.4.A.4 Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
  • 4.4.A.5 When an array stores object references, the attributes can be modified by calling methods on the enhanced for loop variable. This does not change the object references stored in the array.
  • 4.4.A.6 Code written using an enhanced for loop to traverse elements in an array can be rewritten using an indexed for loop or a while loop.

来源:美国大学理事会 AP 课程与考试说明

用一个 for 循环(给出索引)或一个增强 for / for-each(enhanced for / for-each)循环(给出每个值,只读)遍历(traverse)一个数组:

for (int i = 0; i < a.length; i++) { a[i] *= 2; }   // can modify
for (int v : a) { System.out.println(v); }          // read each value
词汇表 训练
英文 中文 拼音
Traverse 遍历 biàn lì
4.5

实现数组算法

大纲
Learning ObjectiveEssential Knowledge

4.5.A
Develop code for standard and original algorithms for a particular context or specification that involves arrays and determine the result of these algorithms.

  • 4.5.A.1 There are standard algorithms that utilize array traversals to:
    • determine a minimum or maximum value
    • compute a sum or average
    • determine if at least one element has a particular property
    • determine if all elements have a particular property
    • determine the number of elements having a particular property
    • access all consecutive pairs of elements
    • determine the presence or absence of duplicate elements
    • shift or rotate elements left or right
    • reverse the order of the elements

来源:美国大学理事会 AP 课程与考试说明

掌握这些模式:计算一个平均、找最大/最小计数满足一个条件的项、检查一个重复,和反转移位元素。每一个都是一个带连续结果的遍历:

int sum = 0;
for (int v : a) sum += v;
double avg = (double) sum / a.length;
4.6

使用文本文件

大纲
Learning ObjectiveEssential Knowledge

4.6.A
Develop code to read data from a text file.

  • 4.6.A.1 A file is storage for data that persists when the program is not running. The data in a file can be retrieved during program execution.
  • 4.6.A.2 A file can be connected to the program using the File and Scanner classes.
  • 4.6.A.3 A file can be opened by creating a File object, using the name of the file as the argument of the constructor.
    • File(String str) is the File constructor that accepts a String file name to open for reading, where str is the pathname for the file.
  • 4.6.A.4 When using the File class, it is required to indicate what to do if the file with the provided name cannot be opened. One way to accomplish this is to add throws IOException to the header of the method that uses the file. If the file name is invalid, the program will terminate.
  • 4.6.A.5 The File and IOException classes are part of the java.io package. An import statement must be used to make these classes available for use in the program.
  • 4.6.A.6 The following Scanner methods and constructor—including what they do and when they are used—are part of the Java Quick Reference:
    • Scanner(File f) is the Scanner constructor that accepts a File for reading.
    • int nextInt() returns the next int read from the file or input source if available. If the next int does not exist or is out of range, it will result in an InputMismatchException.
    • double nextDouble() returns the next double read from the file or input source. If the next double does not exist, it will result in an InputMismatchException.
    • boolean nextBoolean() returns the next boolean read from the file or input source. If the next boolean does not exist, it will result in an InputMismatchException.
    • String nextLine() returns the next line of text as a String read from the file or input source; can return the empty string if called immediately after another Scanner method that is reading from the file or input source.
    • String next() returns the next String read from the file or input source.
    • boolean hasNext() returns true if there is a next item to read in the file or input source; returns false otherwise.
    • void close() closes this scanner.
    • Exclusion statement: Accepting input from the keyboard is outside the scope of the AP Computer Science A course and exam.
  • 4.6.A.7 Using nextLine and the other Scanner methods together on the same input source sometimes requires code to adjust for the methods' different ways of handling whitespace.
    • Exclusion statement: Writing or analyzing code that uses both nextLine and other Scanner methods on the same input source is outside the scope of the AP Computer Science A course and exam.
  • 4.6.A.8 The following additional String method—including what it does and when it is used—is part of the Java Quick Reference:
    • String[] split(String del) returns a String array where each element is a substring of this String, which has been split around matches of the given expression del.
    • Exclusion statement: The parameter del uses a format called a regular expression. Writing or analyzing code that uses any of the special properties of regular expressions (e.g., \\*, \\.) is outside the scope of the AP Computer Science A course and exam.
  • 4.6.A.9 A while loop can be used to detect if the file still contains elements to read by using the hasNext method as the condition of the loop.
  • 4.6.A.10 A file should be closed when the program is finished using it. The close method from Scanner is called to close the file.

来源:美国大学理事会 AP 课程与考试说明

FileIOExceptionjava.io 里,所以一个读文件的程序需要 import java.io.*;。打开一个文件可能失败(它也许不存在),Java 强制你处理这一点——最简单的方式是在方法头上加 throws IOException。然后一个 Scanner 逐行读文件,用 hasNext... 在读之前测试:

import java.io.*;
...
public static void readFile() throws IOException {
    Scanner f = new Scanner(new File("data.txt"));
    while (f.hasNextLine()) {
        String line = f.nextLine();
    }
}

nextInt()nextDouble()nextBoolean() 读有类型的记号时,如果下一个记号是错误的类型,会抛出一个 InputMismatchException——例如当文件里下一个东西是单词 cat 时调用 nextInt()

4.7

包装类

大纲
Learning ObjectiveEssential Knowledge

4.7.A
Develop code to use Integer and Double objects from their primitive counterparts and determine the result of using these objects.

  • 4.7.A.1 The Integer class and Double class are part of the java.lang package. An Integer object is immutable, meaning once an Integer object is created, its attributes cannot be changed. A Double object is immutable, meaning once a Double object is created, its attributes cannot be changed.
  • 4.7.A.2 Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Java compiler applies autoboxing when a primitive value is:
    • passed as a parameter to a method that expects an object of the corresponding wrapper class
    • assigned to a variable of the corresponding wrapper class
  • 4.7.A.3 Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. The Java compiler applies unboxing when a wrapper class object is:
    • passed as a parameter to a method that expects a value of the corresponding primitive type
    • assigned to a variable of the corresponding primitive type
  • 4.7.A.4 The following class Integer method—including what it does and when it is used—is part of the Java Quick Reference:
    • static int parseInt(String s) returns the String argument as an int.
  • 4.7.A.5 The following class Double method—including what it does and when it is used—is part of the Java Quick Reference:
    • static double parseDouble(String s) returns the String argument as a double.

来源:美国大学理事会 AP 课程与考试说明

一个 ArrayList 存储对象,不是基本类型,所以一个基本类型被包装在一个对象里:Integer 包装 int,Double 包装 double。Java 用自动装箱(autoboxing)(intInteger)和拆箱(unboxing)(再回去)自动做这个,所以你能写 list.add(5)int x = list.get(0)

词汇表 训练
英文 中文 拼音
autoboxing 自动装箱 zì dòng zhuāng xiāng
4.8

ArrayList 方法

大纲
Learning ObjectiveEssential Knowledge

4.8.A
Develop code for collections of related objects using ArrayList objects and determine the result of calling methods on these objects.

  • 4.8.A.1 An ArrayList object is mutable in size and contains object references.
  • 4.8.A.2 The ArrayList constructor ArrayList() constructs an empty list.
  • 4.8.A.3 Java allows the generic type ArrayList<E>, where the type parameter E specifies the type of the elements. When ArrayList<E> is specified, the types of the reference parameters and return type when using the ArrayList methods are type E. ArrayList<E> is preferred over ArrayList. For example, ArrayList<String> names = new ArrayList<String>(); allows the compiler to find errors that would otherwise be found at run-time.
  • 4.8.A.4 The ArrayList class is part of the java.util package. An import statement must be used to make this class available for use in the program.
  • 4.8.A.5 The following ArrayList methods—including what they do and when they are used—are part of the Java Quick Reference:
    • int size() returns the number of elements in the list.
    • boolean add(E obj) appends obj to end of list; returns true.
    • void add(int index, E obj) inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size.
    • E get(int index) returns the element at position index in the list.
    • E set(int index, E obj) replaces the element at position index with obj; returns the element formerly at position index.
    • E remove(int index) removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index.
  • 4.8.A.6 The indices for an ArrayList start at 0 and end at the number of elements - 1.

来源:美国大学理事会 AP 课程与考试说明

ArrayList 的底层实现

一个 ArrayList(动态数组)在你添加或移除项时增长和收缩。用 <> 里的元素类型声明它:

ArrayList<String> names = new ArrayList<String>();
names.add("Amy");           // append
names.add(0, "Bob");        // insert at index
names.get(0);               // read
names.set(1, "Cara");       // replace
names.remove(0);            // delete, shifts the rest left
names.size();               // count (a method, unlike array.length)
词汇表 训练
英文 中文 拼音
ArrayList 动态数组 dòng tài shù zǔ
4.9

ArrayList 遍历

大纲
Learning ObjectiveEssential Knowledge

4.9.A
Develop code used to traverse the elements of an ArrayList and determine the results of these traversals.

  • 4.9.A.1 Traversing an ArrayList is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an ArrayList.
  • 4.9.A.2 Deleting elements during a traversal of an ArrayList requires the use of special techniques to avoid skipping elements.
  • 4.9.A.3 Attempting to access an index value outside of its range will result in an IndexOutOfBoundsException.
  • 4.9.A.4 Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.

来源:美国大学理事会 AP 课程与考试说明

用一个索引循环或一个 for-each 循环遍历,就像数组(用 size()get(i)):

for (int i = 0; i < list.size(); i++) { ... list.get(i) ... }
for (String s : list) { ... }

考试技能: 当在一个索引循环里移除项时,要么向后循环,要么在一次移除之后递增 i ——否则移除会把元素向左移动而你跳过一个。而且绝不要在用一个 for-each 循环遍历一个 ArrayList 时添加或移除元素:在循环中途改变它的大小会抛出一个 ConcurrentModificationException,所以每当你必须移除时用一个索引循环(向后,如上)。

4.10

实现 ArrayList 算法

大纲
Learning ObjectiveEssential Knowledge

4.10.A
Develop code for standard and original algorithms for a particular context or specification that involve ArrayList objects and determine the result of these algorithms.

  • 4.10.A.1 There are standard ArrayList algorithms that utilize traversals to:
    • determine a minimum or maximum value
    • compute a sum or average
    • determine if at least one element has a particular property
    • determine if all elements have a particular property
    • determine the number of elements having a particular property
    • access all consecutive pairs of elements
    • determine the presence or absence of duplicate elements
    • shift or rotate elements left or right
    • reverse the order of the elements
    • insert elements
    • delete elements
  • 4.10.A.2 Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously.

来源:美国大学理事会 AP 课程与考试说明

与数组相同的算法——最大/最小、计数、求和——加上数组不能轻易做的插入删除。一个常见的任务是移除所有匹配一个条件的元素,小心地处理索引移位。

4.11

二维数组的创建与访问

大纲
Learning ObjectiveEssential Knowledge

4.11.A
Develop code used to represent collections of related data using two-dimensional (2D) array objects.

  • 4.11.A.1 A 2D array is stored as an array of arrays. Therefore, the way 2D arrays are created and indexed is similar to 1D array objects. The size of a 2D array is established at the time of creation and cannot be changed. 2D arrays can store either primitive data or object reference data.
    • Exclusion statement: Nonrectangular 2D array objects are outside the scope of the AP Computer Science A course and exam.
  • 4.11.A.2 When a 2D array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
  • 4.11.A.3 The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays; for example, int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };.
  • 4.11.A.4 The square brackets [row][col] are used to access and modify an element in a 2D array. For the purposes of the exam, when accessing the element at arr[first][second], the first index is used for rows, the second index is used for columns.
  • 4.11.A.5 A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index.
  • 4.11.A.6 The number of rows contained in a 2D array can be accessed through the length attribute. The valid row index values for a 2D array are 0 through one less than the number of rows or the length of the array, inclusive. The number of columns contained in a 2D array can be accessed through the length attribute of one of the rows. The valid column index values for a 2D array are 0 through one less than the number of columns or the length of any given row of the array, inclusive. For example, given a 2D array named values, the number of rows is values.length and the number of columns is values[0].length. Using an index value outside of these ranges will result in an ArrayIndexOutOfBoundsException.

来源:美国大学理事会 AP 课程与考试说明

一个 2D 数组(2D array)是一个网格(行和列)——一个数组的数组:

一个二维数组(一张表),带行和列索引
一个二维数组(一张表),带行和列索引
int[][] grid = new int[3][4];   // 3 rows, 4 columns
grid[r][c] = 7;                 // row r, column c
int rows = grid.length;         // 3
int cols = grid[0].length;      // 4
探索

Index a 2D array by row and column

A 2D array is a grid addressed by [row][col]. Move the indices and watch which cell they select — row first, then column, both counting from 0.

词汇表 训练
英文 中文 拼音
2D array 二维数组 èr wéi shù zǔ
4.12

二维数组遍历

大纲
Learning ObjectiveEssential Knowledge

4.12.A
Develop code used to traverse the elements in a 2D array and determine the result of these traversals.

  • 4.12.A.1 Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects. Nested iteration statements can be written to traverse the 2D array in row-major order, column-major order, or a uniquely defined order. Row-major order refers to an ordering of 2D array elements where traversal occurs across each row, whereas column-major order traversal occurs down each column.
  • 4.12.A.2 The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhanced for loop variable must be the same type as the elements stored in the 1D array. Assigning a new value to the enhanced for loop variable does not change the value stored in the array.

来源:美国大学理事会 AP 课程与考试说明

遍历二维数组

嵌套循环(nested loops)访问每个单元格——外层遍历行、内层遍历列(行主序(row-major order)):

for (int r = 0; r < grid.length; r++)
    for (int c = 0; c < grid[0].length; c++)
        System.out.print(grid[r][c]);
词汇表 训练
英文 中文 拼音
row-major order 行主序 xíng zhǔ xù
4.13

实现二维数组算法

大纲
Learning ObjectiveEssential Knowledge

4.13.A
Develop code for standard and original algorithms for a particular context or specification that involves 2D arrays and determine the result of these algorithms.

  • 4.13.A.1 There are standard algorithms that utilize 2D array traversals to:
    • determine a minimum or maximum value of all the elements or for a designated row, column, or other subsection
    • compute a sum or average of all the elements or for a designated row, column, or other subsection
    • determine if at least one element has a particular property in the entire 2D array or for a designated row, column, or other subsection
    • determine if all elements of the 2D array or a designated row, column, or other subsection have a particular property
    • determine the number of elements in the 2D array or in a designated row, column, or other subsection having a particular property
    • access all consecutive pairs of elements
    • determine the presence or absence of duplicate elements in the 2D array or in a designated row, column, or other subsection
    • shift or rotate elements in a row left or right or in a column up or down
    • reverse the order of the elements in a row or column

来源:美国大学理事会 AP 课程与考试说明

典型的网格任务:求一行或一列的和、找网格里的最大值、计数匹配的单元格,或求一条对角线的和(r == c 的地方)。每一个都是一个带连续结果的嵌套遍历。

4.14

查找算法

大纲
Learning ObjectiveEssential Knowledge

4.14.A
Develop code used for linear search algorithms to search for specific information in a collection and determine the results of executing a search.

  • 4.14.A.1 Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList.
  • 4.14.A.2 When applying linear search algorithms to 2D arrays, each row must be accessed then linear search applied to each row of the 2D array.

来源:美国大学理事会 AP 课程与考试说明

二分查找
  • 线性搜索(linear search)依次检查每个元素——在任何列表上起作用,取最多 $n$ 步。
  • 二分搜索(binary search)只在一个排序的列表上起作用:检查中间、然后丢弃不能包含目标的那一半,重复。它取约 $\log_2 n$ 步——在大数据上快得多。
二分搜索在每一步把范围减半
二分搜索在每一步把范围减半
线性搜索依次检查每个元素直到目标被找到
线性搜索依次检查每个元素直到目标被找到
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
    int mid = (lo + hi) / 2;
    if (a[mid] == target) return mid;
    else if (a[mid] < target) lo = mid + 1;
    else hi = mid - 1;
}

考试技能: 二分搜索需要排序的数据;知道它做多少次比较以及 lohimid 如何更新。

Worked example. 在排序的数组 {3, 9, 14, 23, 31, 42, 55}(索引 06)里搜索 target = 40。开始 lo=0, hi=6:

  • mid = (0+6)/2 = 3,a[3]=23 < 40,所以 lo = 4;
  • mid = (4+6)/2 = 5,a[5]=42 > 40,所以 hi = 4;
  • mid = (4+4)/2 = 4,a[4]=31 < 40,所以 lo = 5;
  • 现在 lo (5) > hi (4),所以循环结束——40 不存在

每一步把范围减半,所以即使这次未命中也只取三次比较。

探索

Compare linear and binary search

Linear search checks every element in turn; binary search halves a sorted list each step. Watch binary search reach the target in far fewer comparisons.

词汇表 训练
英文 中文 拼音
Linear search 线性搜索 xiàn xìng sōu suǒ
Binary search 二分搜索 èr fēn sōu suǒ
4.15

排序算法

大纲
Learning ObjectiveEssential Knowledge

4.15.A
Determine the result of executing each step of sorting algorithms to sort the elements of a collection.

  • 4.15.A.1 Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList.
  • 4.15.A.2 Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
  • 4.15.A.3 Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.

来源:美国大学理事会 AP 课程与考试说明

插入排序
冒泡排序
  • 选择排序(selection sort)反复找到最小的剩余元素并把它交换到位。
  • 插入排序(insertion sort)增长一个排序的前部,把每个新元素插入到它所属的地方。
一个插入排序,一趟一趟地把每个键移到位
一个插入排序,一趟一趟地把每个键移到位

两者都简单,平均取约 $n^2$ 步——对小数组还行。能够跟踪每一趟之后的数组。

探索

Watch a sorting algorithm order a list

A sort rearranges elements into order. Step through selection/insertion sort to see the sorted region grow one element at a time.

词汇表 训练
英文 中文 拼音
Selection sort 选择排序 xuǎn zé pái xù
Insertion sort 插入排序 chā rù pái xù
4.16

递归

大纲
Learning ObjectiveEssential Knowledge

4.16.A
Determine the result of calling recursive methods.

  • 4.16.A.1 A recursive method is a method that calls itself. Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call. Recursion is another form of repetition.
  • 4.16.A.2 Each recursive call has its own set of local variables, including the parameters. Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop.
  • 4.16.A.3 Any recursive solution can be replicated through the use of an iterative approach and vice versa.
    • Exclusion statement: Writing recursive code is outside the scope of the AP Computer Science A course and exam.

来源:美国大学理事会 AP 课程与考试说明

递归与调用栈

递归(recursion)是一个在一个更小的输入上调用它自己的方法。它需要一个停止调用的基本情况(base case),和一个朝基本情况移动的递归情况(recursive case):

public static int factorial(int n) {
    if (n <= 1) return 1;          // base case
    return n * factorial(n - 1);   // recursive case
}

没有一个可达的基本情况,递归从不停止(一个栈溢出)。

递归和迭代是可以互换的。任何递归解法都能用一个循环(迭代方式)改写,而任何循环也都能用递归改写 —— 它们解决的是同一类问题。上面的 factorial 与一个迭代版本效果完全相同:

public static int factorial(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++) result *= i;   // same answer, no self-call
    return result;
}

所以这个选择关乎清晰度,而非能力:对于具有自相似结构的问题(树、归并排序),递归读起来很自然;而迭代则避免了每一步都压入一个调用帧的内存开销。考试可能会要求你把其中一种转换成另一种。

探索

Unfold a recursive call

A recursive method calls itself on a smaller input until it hits a base case, then the results fold back up. Step through to watch the calls stack and unwind.

词汇表 训练
英文 中文 拼音
Recursion 递归 dì guī
base case 基本情况 jī běn qíng kuàng
4.17

递归查找与排序

大纲
Learning ObjectiveEssential Knowledge

4.17.A
Determine the result of executing recursive algorithms that use strings or collections.

  • 4.17.A.1 Recursion can be used to traverse String objects, arrays, and ArrayList objects.

4.17.B
Determine the result of each iteration of a binary search algorithm used to search for information in a collection.

  • 4.17.B.1 Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each recursive call until the desired value is found or all elements have been eliminated.
  • 4.17.B.2 Binary search is typically more efficient than linear search.
    • Exclusion statement: Search algorithms other than linear and binary search are outside the scope of the AP Computer Science A course and exam.
  • 4.17.B.3 The binary search algorithm can be written either iteratively or recursively.

4.17.C
Determine the result of each iteration of the merge sort algorithm when used to sort a collection.

  • 4.17.C.1 Merge sort is a recursive sorting algorithm that can be used to sort elements in an array or ArrayList.
    • Exclusion statement: Sorting algorithms other than selection, insertion, and merge sort are outside the scope of the AP Computer Science A course and exam.
  • 4.17.C.2 Merge sort repeatedly divides an array into smaller subarrays until each subarray is one element and then recursively merges the sorted subarrays back together in sorted order to form the final sorted array.

来源:美国大学理事会 AP 课程与考试说明

归并排序

递归驱动高效的算法。二分搜索能被递归地写(搜索正确的那一半)。归并排序(merge sort)把数组分成一半、递归地排序每一半,然后归并两个排序的一半——取约 $n\log_2 n$ 步,在大数据上比选择或插入排序快得多。

归并排序把数组分裂到单个元素,然后把排序的一半向上归并
归并排序把数组分裂到单个元素,然后把排序的一半向上归并

Worked example. 跟踪 factorial(4)。每个调用推迟给一个更小的:factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1)factorial(1) 命中基本情况并返回 1,所以调用向内展开:2 * 1 = 2,然后 3 * 2 = 6,然后 4 * 6 = 24。把每个调用写在它返回值的上方是跟踪递归的可靠方式。

考试技能: 通过写出每个调用和它的返回值来跟踪一个递归方法,并知道归并排序的效率($n\log n$)击败 $n^2$ 的简单排序。

词汇表 训练
英文 中文 拼音
Merge sort 归并排序 guī bìng pái xù
4.17

考试技巧

  • 权衡收集数据的好处和害处——这个单元通过简短的书面论证考查,不是代码。
  • 保护个人身份信息(PII)(personally identifiable information)并在上下文里解释隐私和安全风险。
  • 命名真实的害处:数据泄露、监视,和来自不具代表性数据的算法偏见
  • 当你重用代码或数据时尊重知识产权和许可。
  • 给出一个具体的、有理由的答案——一个模糊的"它可能是坏的"不赢得分数。

本主题的互动课程

逐步学习,并即时检测练习。

AP 计算机科学 A历年真题

AP 计算机科学 A的更多主题

登录或创建账号

IGCSE, A-Level & AP