Implementing
Array Algorithms
Master the essential patterns for traversing, searching, and manipulating arrays in Java: the building blocks of every AP CSA solution.
What Is an Array?
An array is a fixed-size, ordered collection of elements, all of the same type. Each element is stored at a numbered position called an index, starting at 0 and ending at length - 1.
Why Array Algorithms Matter
Nearly every data-processing task reduces to a pattern on arrays. On the AP exam, you will be expected to write, trace, and debug algorithms that traverse, modify, and analyze arrays.
The Traversal Pattern
A traversal visits every element of an array exactly once. In Java, the two standard forms are the indexed for loop and the enhanced for loop.
Core Rule: Bounds & Access
The Accumulation Pattern
An accumulator variable is initialized before the loop and updated inside it. This pattern computes a sum, product, count, or builds a string.
for Loop vs Enhanced for
| Indexed for | Enhanced for | |
|---|---|---|
| Syntax | for(int i=0; ...) | for(int v : arr) |
| Access index? | Yes | No |
| Modify elements? | Yes | No (copy only) |
| Traverse subset? | Yes (change bounds) | No (full pass) |
| Readability | Moderate | Cleaner |
How to Apply an Array Algorithm
Example 1: Finding the Maximum
Example 2: Linear Search
Example 3: Right Shift & Insert
To insert a value at index \( k \), shift all elements from index \( k \) onward one position to the right, then place the new value.
Example 4: Reversing an Array
Example 5: Counting Duplicates
Comparing every pair of elements requires a nested loop. The inner loop starts at \( i + 1 \) to avoid counting each pair twice.
Example 6: Left Shift (Remove at Index)
To remove the element at index \( k \), shift all elements after it one position to the left, then handle the last slot.
Common Mistakes
Algorithm Summary
| Algorithm | Pattern | Key Detail |
|---|---|---|
| Sum / Average | Accumulate | Init to 0 |
| Min / Max | Accumulate | Init to arr[0] |
| Linear Search | Search | Return -1 if not found |
| Count matches | Accumulate + filter | if inside loop |
| Reverse | Two-pointer swap | Loop to length/2 |
| Right Shift | Backward iteration | Start at end |
| Left Shift | Forward iteration | Start at removal index |
Question 1 of 5
What is the output of the following code?
int[] a = {4, 9, 2, 7};
int s = 0;
for (int v : a) { s += v; }
System.out.println(s);
Question 2 of 5
Which loop correctly finds the minimum value in an int[] named data?
Question 3 of 5
Given int[] arr = {1, 2, 3, 4, 5}, what is arr[arr.length - 1]?
Question 4 of 5
You want to double every element in an array. Which approach works?
Question 5 of 5
After running this code, what does arr contain?
int[] arr = {10, 20, 30, 40};
for(int i = 0; i < arr.length / 2; i++) {
int t = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = t;
}