AP Computer Science A

Data collections

Reason about search, sort, and recursion

Trace algorithm boundaries, recursive calls, and how input size affects work.

Examples use Java. Read and trace them here; run them in a Java environment. The studio executes pseudocode.

Identify the algorithm's promise

Linear search inspects each element until it finds a match or reaches the end. Binary search maintains a sorted candidate range and discards the half that cannot contain the target. It is not correct to apply binary search to an arbitrary unsorted array.

For insertion sort, the prefix before the current position is already sorted. Insert the next element into that prefix by shifting larger values right. Use a small trace to check that moving values does not overwrite an element you still need.

Interactive
12
25
39
412
517
Looking for 12. Start at item 1.
Step 1 / 5

Every recursion needs progress and a base case

A recursive method calls itself on a smaller or simpler problem. The base case returns without another call. sumTo(3) waits for sumTo(2), which waits for sumTo(1), which waits for sumTo(0). Returns then travel back up the call stack.

The method below has the precondition n >= 0 and prints 6 for n = 3. Tracing only the calls is insufficient: also trace the pending additions during the returns. Test n = 0 to verify the stopping condition.

public class Demo {
    public static int sumTo(int n) {
        if (n == 0) { return 0; }
        return n + sumTo(n - 1);
    }
    public static void main(String[] args) {
        System.out.println(sumTo(3));
    }
}

Check yourself

What goes wrong if the recursive method calls sumTo(n) instead of sumTo(n - 1)?Show answer

The problem does not get smaller. For positive n, the base case is never reached and the call stack eventually overflows.

References used to build these lessons

We used these official documents as references when building this course's lessons. They are the sources for the syllabus structure and course requirements.

College Board · Effective fall 2025