Skip to content

Data Collections

AP Computer Science A · Topic 4

Train
4.1

The Ethics of Collecting Data

Syllabus
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.

Source: College Board AP Course and Exam Description

Programs that gather data raise questions of privacy 隐私 and consent 同意. Collect only what is needed, protect it, and be honest about its use. Data can carry bias 偏见 if it does not represent everyone fairly, leading to unfair results – a responsibility that comes with storing information.

Vocabulary Train
English Chinese Pinyin
privacy 隐私 yǐn sī
consent 同意 tóng yì
bias 偏见 piān jiàn
4.2

Why We Need Data Structures

Syllabus
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.

Source: College Board AP Course and Exam Description

A single variable holds one value; real problems need to store many related values – a class roster, pixels, sensor readings. A data structure 数据结构 organizes a collection so we can store, find, and process items efficiently. The AP course uses three: the array, the ArrayList, and the 2D array.

Vocabulary Train
English Chinese Pinyin
data structure 数据结构 shù jù jié gòu
4.3

Making and Reading an Array

Syllabus
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.

Source: College Board AP Course and Exam Description

An array 数组 is a fixed-size, ordered collection of same-type values. Indices run from 0 to length - 1:

A one-dimensional array (a list) with its indices and bounds A one-dimensional array (a list) with its indices and bounds

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)

Accessing an index outside 0..length-1 throws an ArrayIndexOutOfBoundsException.

Vocabulary Train
English Chinese Pinyin
array 数组 shù zǔ
4.4

Visiting Every Element of an Array

Syllabus
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.

Source: College Board AP Course and Exam Description

Traverse 遍历 an array with a for loop (gives the index) or an enhanced for / for-each loop (gives each value, read-only):

for (int i = 0; i < a.length; i++) { a[i] *= 2; }   // can modify
for (int v : a) { System.out.println(v); }          // read each value
Vocabulary Train
English Chinese Pinyin
Traverse 遍历 biàn lì
4.5

Standard Array Algorithms

Syllabus
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

Source: College Board AP Course and Exam Description

Master these patterns: compute a sum or average, find the max/min, count items meeting a condition, check for a duplicate, and reverse or shift elements. Each is a traversal with a running result:

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

Reading Data from a Text File

Syllabus
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.

Source: College Board AP Course and Exam Description

File and IOException live in java.io, so a program that reads a file needs import java.io.*;. Opening a file can fail (it might not exist), and Java forces you to handle that – the simplest way is to add throws IOException to the method header. A Scanner then reads the file line by line, using hasNext... to test before reading:

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

Reading typed tokens with nextInt(), nextDouble(), or nextBoolean() throws an InputMismatchException if the next token is the wrong type – for example calling nextInt() when the next thing in the file is the word cat.

4.7

Wrapping a Number in an Object

Syllabus
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.

Source: College Board AP Course and Exam Description

An ArrayList stores objects, not primitives, so a primitive is wrapped in an object: Integer wraps int, Double wraps double. Java does this with autoboxing 自动装箱 (int to Integer) and unboxing (back again) automatically, so you can write list.add(5) and int x = list.get(0).

Vocabulary Train
English Chinese Pinyin
autoboxing 自动装箱 zì dòng zhuāng xiāng
4.8

The ArrayList Toolbox

Syllabus
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.

Source: College Board AP Course and Exam Description

What an ArrayList really is

An ArrayList 动态数组 grows and shrinks as you add or remove items. Declare it with the element type in <>:

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)
Vocabulary Train
English Chinese Pinyin
ArrayList 动态数组 dòng tài shù zǔ
4.9

Visiting Every Element of an ArrayList

Syllabus
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.

Source: College Board AP Course and Exam Description

Traverse with an index loop or a for-each loop, just like arrays (use size() and get(i)):

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

Exam skill: when removing items in an index loop, either loop backwards or do not increment i after a removal – otherwise removing shifts elements left and you skip one. And never add or remove elements while traversing an ArrayList with a for-each loop: changing its size mid-loop throws a ConcurrentModificationException, so use an index loop (backwards, as above) whenever you must remove.

4.10

Standard ArrayList Algorithms

Syllabus
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.

Source: College Board AP Course and Exam Description

The same algorithms as arrays – max/min, count, sum – plus insertion and deletion that arrays cannot do easily. A common task is to remove all elements matching a condition, handling the index-shift carefully.

4.11

Grids: Two-Dimensional Arrays

Syllabus
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.

Source: College Board AP Course and Exam Description

A 2D array 二维数组 is a grid (rows and columns) – an array of arrays:

A two-dimensional array (a table) with row and column indices A two-dimensional array (a table) with row and column indices

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
Explore

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.

Vocabulary Train
English Chinese Pinyin
2D array 二维数组 èr wéi shù zǔ
4.12

Walking Through a Grid

Syllabus
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.

Source: College Board AP Course and Exam Description

Traversing a 2-D array

Visit every cell with nested loops – the outer over rows, the inner over columns (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]);
Vocabulary Train
English Chinese Pinyin
row-major order 行主序 xíng zhǔ xù
4.13

Standard 2D Array Algorithms

Syllabus
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

Source: College Board AP Course and Exam Description

Typical grid tasks: sum a row or column, find the max in the grid, count matching cells, or sum a diagonal (where r == c). Each is a nested traversal with a running result.

4.14

Finding a Value: Linear and Binary Search

Syllabus
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.

Source: College Board AP Course and Exam Description

Binary search: halve and conquer
  • Linear search 线性搜索 checks each element in turn – works on any list, taking up to $n$ steps.
  • Binary search 二分搜索 works only on a sorted list: check the middle, then discard the half that cannot contain the target, repeating. It takes about $\log_2 n$ steps – far faster on large data.

Binary search halves the range at each step Binary search halves the range at each step

Linear search checks every element in turn until the target is found Linear search checks every element in turn until the target is found

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;
}

Exam skill: binary search requires sorted data; know how many comparisons it makes and how lo, hi, mid update.

Worked example. Search for target = 40 in the sorted array {3, 9, 14, 23, 31, 42, 55} (indices 06). Start lo=0, hi=6:

  • mid = (0+6)/2 = 3, a[3]=23 < 40, so lo = 4;
  • mid = (4+6)/2 = 5, a[5]=42 > 40, so hi = 4;
  • mid = (4+4)/2 = 4, a[4]=31 < 40, so lo = 5;
  • now lo (5) > hi (4), so the loop ends – 40 is not present.

Each step halved the range, so even this miss took only three comparisons.

Explore

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.

Vocabulary Train
English Chinese Pinyin
Linear search 线性搜索 xiàn xìng sōu suǒ
Binary search 二分搜索 èr fēn sōu suǒ
4.15

Putting Data in Order: Selection and Insertion Sort

Syllabus
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.

Source: College Board AP Course and Exam Description

Insertion sort
Bubble sort, pass by pass
  • Selection sort 选择排序 repeatedly finds the smallest remaining element and swaps it into place.
  • Insertion sort 插入排序 grows a sorted front, inserting each new element where it belongs.

An insertion sort, shifting each key into place pass by pass An insertion sort, shifting each key into place pass by pass

Both are simple and take about $n^2$ steps on average – fine for small arrays. Be able to trace the array after each pass.

Explore

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.

Vocabulary Train
English Chinese Pinyin
Selection sort 选择排序 xuǎn zé pái xù
Insertion sort 插入排序 chā rù pái xù
4.16

Methods That Call Themselves: Recursion

Syllabus
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.

Source: College Board AP Course and Exam Description

Recursion & the call stack

Recursion 递归 is a method that calls itself on a smaller input. It needs a base case 基本情况 that stops the calls, and a recursive case that moves toward the base:

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

Without a reachable base case, recursion never stops (a stack overflow).

Recursion and iteration are interchangeable. Any recursive solution can be rewritten with a loop (an iterative approach), and any loop can be rewritten with recursion - they solve the same problems. The factorial above is identical in effect to an iterative version:

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;
}

So the choice is about clarity, not capability: recursion reads naturally for problems with a self-similar structure (trees, merge sort), while iteration avoids the memory cost of stacking a call frame per step. The exam may ask you to convert one into the other.

Explore

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.

Vocabulary Train
English Chinese Pinyin
Recursion 递归 dì guī
base case 基本情况 jī běn qíng kuàng
4.17

Recursive Search and Merge Sort

Syllabus
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.

Source: College Board AP Course and Exam Description

Merge sort: split, then merge

Recursion powers efficient algorithms. Binary search can be written recursively (search the correct half). Merge sort 归并排序 splits the array in half, sorts each half recursively, then merges the two sorted halves – taking about $n\log_2 n$ steps, much faster than selection or insertion sort on large data.

Merge sort splits the array to single elements, then merges sorted halves back up Merge sort splits the array to single elements, then merges sorted halves back up

Worked example. Trace factorial(4). Each call defers to a smaller one: factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1). factorial(1) hits the base case and returns 1, so the calls unwind inward: 2 * 1 = 2, then 3 * 2 = 6, then 4 * 6 = 24. Writing each call above its returned value is the reliable way to trace recursion.

Exam skill: trace a recursive method by writing out each call and its return value, and know that merge sort's efficiency ($n\log n$) beats the $n^2$ simple sorts.

Vocabulary Train
English Chinese Pinyin
Merge sort 归并排序 guī bìng pái xù
4.17

Exam tips

  • Weigh both benefits and harms of collecting data — this unit is tested through short written justification, not code.
  • Protect personally identifiable information (PII) and explain privacy and security risks in context.
  • Name real harms: data breaches, surveillance, and algorithmic bias from unrepresentative data.
  • Respect intellectual property and licensing when you reuse code or data.
  • Give a specific, reasoned answer — a vague "it could be bad" earns no marks.

Log in or create account

IGCSE & A-Level