Arrays - Complete Interactive Lesson
Part 1: Core Concepts
📊 Array Algorithms
Part 1 of 7 — Searching, Shifting, and Array Manipulation
Linear Search
public int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Return index of target
}
}
return -1; // Not found
}
| Property | Detail |
|---|---|
| Best case | Target is at index 0: 1 comparison |
| Worst case | Target not found: n comparisons |
| Average case | n/2 comparisons |
| Works on | Sorted or unsorted arrays |
Shifting Elements
Removing an Element (Shift Left)
// Remove element at index 2 from {10, 20, 30, 40, 50}
// Shift elements left to fill the gap
for (int i = 2; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
// Result: {10, 20, 40, 50, 50}
// Note: array size unchanged; last element duplicated
Inserting an Element (Shift Right)
// Insert 25 at index 2 in {10, 20, 30, 40, 50}
// Shift elements right first (start from end!)
for (int i = arr.length - 1; i > 2; i--) {
arr[i] = arr[i - 1];
}
arr[2] = 25;
// Result: {10, 20, 25, 30, 40}
// Note: last element (50) is lost
🔑 Shifting direction matters! Shift LEFT = go forward. Shift RIGHT = go backward to avoid overwriting.
Concept Check 🎯
Reversing an Array
public void reverse(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
}
Key insight: Only loop through half the array. Swap element i with element (length - 1 - i).
Consecutive Pairs
// Check if any consecutive elements are equal
public boolean hasConsecutiveDuplicates(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] == arr[i + 1]) {
return true;
}
}
return false;
}
⚠️ Loop to
arr.length - 1(notarr.length) when comparing arr[i] with arr[i + 1] to avoid ArrayIndexOutOfBoundsException.
Selection Sort (Traced on the AP Exam)
for (int i = 0; i < arr.length - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// Swap arr[i] and arr[minIdx]
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
Applied Recall ✍️
-
Linear search checks each element one by one, so in the worst case it makes _______ comparisons for an array of n elements.
-
When comparing consecutive pairs arr[i] and arr[i+1], the loop should run to arr.length - _______.
-
To swap two values, you need a _______ variable to hold one value temporarily.
Choose the Algorithm 🔍
AP Exam Strategy: Array Algorithms
- Linear search returns -1 for not found — check the return value in conditionals
- Shifting arrays is a very common FRQ task — know both left and right shifts
- When shifting RIGHT, start from the END to avoid overwriting
- Reversing only needs length/2 iterations — do not double-swap!
- Know how to write a swap using a temp variable — this is fundamental
- Selection sort and insertion sort are CED algorithms you must be able to trace — they are NOT on the Java Quick Reference, so know how each pass works
AP-Style Application 🎯
Part 2: Standard Algorithms: Totals, Extremes, Counts, and Any/All
📊 Array Algorithms
Part 2 of 7 — Standard Algorithms: Totals, Extremes, Counts, and Any/All
Most array code on the AP exam is built from a handful of standard algorithms (CED Topic 4.5). Part 1 covered linear search, shifting, reversing and neighbor checks. This part covers the algorithms that summarize an array: they read every element and boil the whole array down to one number or one true/false answer.
| Algorithm | Answers the question | Result type |
|---|---|---|
| Sum and average | What is the total? The mean? | int or double |
| Minimum or maximum | What is the extreme value, and where is it? | element or index |
| Count | How many elements meet a condition? | int |
| At least one / all | Does any element qualify? Does every element? | boolean |
| Duplicates and frequency | Does a value repeat? How often does it appear? | boolean or int |
🔑 Key Concept: Every summarizing algorithm has the same three pieces: a variable set up before the loop, an update inside the loop, and an answer used after the loop. Most bugs are in the first or last piece.
Sum and Average
int[] temps = {68, 74, 71, 80, 65, 77};
int sum = 0;
for (int t : temps) {
sum += t;
}
double average = (double) sum / temps.length;
sum ends at 435. The average depends on where the cast goes:
| Expression | Value | Why |
|---|---|---|
sum / temps.length | 72 | int / int is int division: 435 / 6 drops the .5 |
(double) sum / temps.length | 72.5 | the cast turns sum into 435.0 before dividing |
(double) (sum / temps.length) | 72.0 | the parentheses divide first, so the .5 is already gone |
Storing an int quotient in a double variable does not help: double avg = sum / temps.length; stores 72.0.
Extremes: Track the Index
int maxIndex = 0;
for (int i = 1; i < temps.length; i++) {
if (temps[i] > temps[maxIndex]) {
maxIndex = i;
}
}
// maxIndex is 3, and temps[maxIndex] is 80
Keeping the index gives you both answers: the position is maxIndex and the value is temps[maxIndex]. The loop starts at 1 because index 0 is already the first candidate. Changing > to < finds the minimum: index 4, value 65.
Choosing the Starting Value
| Start max at | Correct? | Reason |
|---|---|---|
arr[0] | yes, for any nonempty array | the first element is a real candidate |
Integer.MIN_VALUE | yes | no int is smaller, so the first element replaces it |
0 | no | for {-5, -2, -9} nothing beats 0, so the method reports 0, a value that is not in the array |
The same trap works in reverse: a minimum that starts at 0 reports 0 for {4, 9, 6}.
Ties
For {5, 9, 2, 9}, the test arr[i] > arr[maxIndex] keeps the first 9 and ends with index 1. The test arr[i] >= arr[maxIndex] moves to every later 9 it meets and ends with index 3. Read the specification: "the first occurrence" and "the last occurrence" call for different operators.
🎯 AP Connection: Free-response questions often ask for the index of the largest or smallest element. Returning the value instead of the index loses the point even if the loop is perfect.
Concept Check 🎯
Segment A
int[] nums = {3, 8, 2, 6};
int sum = 0;
for (int n : nums) {
sum += n;
}
double avg = sum / nums.length;
System.out.println(avg);
Segment B
int[] vals = {-3, -8, -1};
int max = 0;
for (int v : vals) {
if (v > max) {
max = v;
}
}
Counting Elements That Meet a Condition
int count = 0;
for (int t : temps) {
if (t > 70) {
count++;
}
}
// count is 4: the values 74, 71, 80 and 77
The count goes up only inside the if, and it is used only after the loop.
At Least One vs. All
public static boolean anyNegative(int[] arr) {
for (int value : arr) {
if (value < 0) {
return true; // one example proves it
}
}
return false; // known only after checking everything
}
public static boolean allEven(int[] arr) {
for (int value : arr) {
if (value % 2 != 0) {
return false; // one counterexample disproves it
}
}
return true;
}
| Question | Return inside the loop | Return after the loop | Empty array returns |
|---|---|---|---|
| Does at least one element qualify? | true when a match appears | false | false |
| Does every element qualify? | false when a counterexample appears | true | true |
The two methods are mirror images. An empty array has no example, so "at least one" is false, and it has no counterexample, so "all" is true.
The Classic Bug: Deciding Too Early
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
return true;
} else {
return false;
}
}
Both branches return, so the loop never gets past index 0: the method answers using the first element only.
Any Duplicates? Check Every Pair Once
Part 1 compared neighbors. A repeated value can be anywhere, so compare every pair of positions:
public static boolean hasDuplicate(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
return true;
}
}
}
return false;
}
- The inner loop starts at
i + 1, so each pair is checked once and no element is compared with itself. Starting at 0 would comparearr[0]with itself and return true for every nonempty array. {4, 1, 7, 1}returns true on the 5th comparison, whenarr[1]meetsarr[3].{6, 2, 8, 3, 5}checks all 4 + 3 + 2 + 1 = 10 pairs and returns false.
Frequency of One Value
public static int countOf(int[] arr, int target) {
int count = 0;
for (int value : arr) {
if (value == target) {
count++;
}
}
return count;
}
countOf(new int[] {4, 7, 4, 2, 7, 7, 1}, 7) returns 3.
Pick the Pattern 🔍
Worked Example: The Most Frequent Value
Task. Return the value that appears most often in a nonempty array. If two values tie, return the one that reaches the top count first.
public static int mostFrequent(int[] arr) {
int best = arr[0];
int bestCount = 0;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[j] == arr[i]) {
count++;
}
}
if (count > bestCount) {
bestCount = count;
best = arr[i];
}
}
return best;
}
Step 1 — See the two algorithms. The inner loop is the frequency count for arr[i]. The outer loop is a maximum search over those counts. count is reset inside the outer loop so every value is counted from zero.
Step 2 — Trace {4, 7, 4, 2, 7, 7, 1}.
| i | arr[i] | count | count > bestCount? | best, bestCount afterward |
|---|---|---|---|---|
| 0 | 4 | 2 | yes (2 > 0) | 4, 2 |
| 1 | 7 | 3 | yes (3 > 2) | 7, 3 |
| 2 | 4 | 2 | no | 7, 3 |
| 3 | 2 | 1 | no | 7, 3 |
| 4 | 7 | 3 | no (3 > 3 is false) | 7, 3 |
| 5 | 7 | 3 | no | 7, 3 |
| 6 | 1 | 1 | no | 7, 3 |
Step 3 — Answer. The method returns 7.
Step 4 — Count the work. The inner comparison runs 7 x 7 = 49 times, because both loops cover the whole array. The value 7 is counted three separate times; the method is simple, not efficient.
Step 5 — Check the tie rule. With >, a later value that only ties the best count does not replace it. Changing the test to >= would let every tie replace it, so the method would return the tied value checked last.
AP-Style Application 🎯
public static boolean allPositive(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
return true;
} else {
return false;
}
}
return true;
}
Part 3: Rearranging Elements: Rotations, Swaps, and Compaction
📊 Array Algorithms
Part 3 of 7 — Rearranging Elements: Rotations, Swaps, and Compaction
Part 1 shifted elements by one position and lost a value off the end. This part keeps every value: it rotates arrays, swaps neighbors, packs values to the front, and builds new arrays when the result has a different length (CED Topic 4.5).
| In this part |
|---|
| Rotating left and right by one, and why loop direction matters |
| Swapping adjacent pairs |
| Compaction: moving chosen values to the front |
| Building a new array instead of changing the old one |
| Worked example: one pass of compare-and-swap |
🔑 Key Concept: An assignment
arr[i] = arr[i + 1]destroys the old value inarr[i]. Before you write a rearranging loop, ask which value would be overwritten before it is copied, and either save it in a variable or loop in the direction that reads it first.
Rotate Left by One
The first element moves to the end and every other element moves one place left.
public static void rotateLeft(int[] arr) {
int first = arr[0]; // save the value that falls off
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = first;
}
{10, 20, 30, 40, 50} becomes {20, 30, 40, 50, 10}. Without first, the last line would have to copy arr[0], which already holds 20, and the result would be {20, 30, 40, 50, 20}.
Rotate Right by One
public static void rotateRight(int[] arr) {
int last = arr[arr.length - 1];
for (int i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last;
}
{10, 20, 30, 40, 50} becomes {50, 10, 20, 30, 40}.
Why the Right Rotation Loops Backward
Suppose the loop ran forward instead: for (int i = 1; i < arr.length; i++) { arr[i] = arr[i - 1]; }
| i | Assignment | Array afterward |
|---|---|---|
| 1 | arr[1] = arr[0] | {10, 10, 30, 40, 50} |
| 2 | arr[2] = arr[1] | {10, 10, 10, 40, 50} |
| 3 | arr[3] = arr[2] | {10, 10, 10, 10, 50} |
| 4 | arr[4] = arr[3] | {10, 10, 10, 10, 10} |
Each step copies the value the previous step just wrote, so 10 spreads across the whole array. Going backward reads each old value before anything overwrites it.
| Move values | Each element copies from | Loop direction | Save first |
|---|---|---|---|
| left | arr[i + 1] | forward, i from 0 up to length - 2 | arr[0] |
| right | arr[i - 1] | backward, i from length - 1 down to 1 | arr[length - 1] |
Both loops stop one short of the far end, which keeps i + 1 and i - 1 inside the array.
Concept Check 🎯
Swapping Adjacent Pairs
Swap elements 0 and 1, then 2 and 3, and so on.
for (int i = 0; i < arr.length - 1; i += 2) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
| Array | Result | Note |
|---|---|---|
{1, 2, 3, 4, 5, 6} | {2, 1, 4, 3, 6, 5} | three swaps |
{1, 2, 3, 4, 5} | {2, 1, 4, 3, 5} | the unpaired last element stays put |
Two details decide whether this works:
- The bound is
arr.length - 1. Withi < arr.length, an odd-length array reaches i = 4 and readsarr[5], throwing an ArrayIndexOutOfBoundsException. - The step is
i += 2. Withi++, each swap carries the same value one step further right:{1, 2, 3, 4, 5}becomes{2, 3, 4, 5, 1}, a left rotation.
Compaction: Move Values to the Front
Task. Move every nonzero value to the front, keeping their order, and fill the rest with zeros.
public static void compact(int[] arr) {
int write = 0; // next open spot at the front
for (int read = 0; read < arr.length; read++) {
if (arr[read] != 0) {
arr[write] = arr[read];
write++;
}
}
while (write < arr.length) {
arr[write] = 0;
write++;
}
}
Trace with {0, 7, 0, 0, 3, 9}:
| read | arr[read] | Copied to | write afterward | Array afterward |
|---|---|---|---|---|
| 0 | 0 | none | 0 | {0, 7, 0, 0, 3, 9} |
| 1 | 7 | index 0 | 1 | {7, 7, 0, 0, 3, 9} |
| 2 | 0 | none | 1 | {7, 7, 0, 0, 3, 9} |
| 3 | 0 | none | 1 | {7, 7, 0, 0, 3, 9} |
| 4 | 3 | index 1 | 2 | {7, 3, 0, 0, 3, 9} |
| 5 | 9 | index 2 | 3 | {7, 3, 9, 0, 3, 9} |
The while loop then zeros indexes 3 to 5, giving {7, 3, 9, 0, 0, 0}. Two index variables move at different speeds: read visits every element, and write advances only when a value is kept. Because write never passes read, nothing is overwritten before it is read. Leaving out the while loop leaves the old values behind: {7, 3, 9, 0, 3, 9}.
Predict the Rearrangement 🔍
Building a New Array Instead
An array's length is fixed when it is created. When the result needs a different length, or the original must stay unchanged, build and return a new array.
Filtering: Count First, Then Fill
public static int[] evensOnly(int[] arr) {
int count = 0;
for (int v : arr) {
if (v % 2 == 0) {
count++;
}
}
int[] result = new int[count];
int k = 0; // next open index in result
for (int v : arr) {
if (v % 2 == 0) {
result[k] = v;
k++;
}
}
return result;
}
evensOnly(new int[] {5, 8, 2, 7, 4}) returns {8, 2, 4}. The first loop finds the size, because the new array must be created with its final length. The second loop needs its own index k: using v's position in arr would skip slots in result or run past its end. With no even values, the method returns an empty array of length 0.
Removing One Position
public static int[] removeAt(int[] arr, int idx) {
int[] result = new int[arr.length - 1];
for (int i = 0; i < idx; i++) {
result[i] = arr[i]; // before idx: same position
}
for (int i = idx + 1; i < arr.length; i++) {
result[i - 1] = arr[i]; // after idx: one position left
}
return result;
}
removeAt(new int[] {10, 20, 30, 40, 50}, 1) returns {10, 30, 40, 50}. Writing result[i] = arr[i] in the second loop would throw an ArrayIndexOutOfBoundsException when i reaches 4, because result has only indexes 0 to 3.
Rotating by k Positions
int n = arr.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[(i + k) % n] = arr[i];
}
Each element jumps k places right, and % n wraps positions past the end back to the front. With k = 2, {10, 20, 30, 40, 50} gives {40, 50, 10, 20, 30}. A k of 7 gives the same result, because 7 % 5 is 2.
| Approach | When to use it | Trade-off |
|---|---|---|
Change arr in place | same length, original not needed | must avoid overwriting values before reading them |
| Return a new array | new length, or original must survive | needs a separate index for the new array |
Worked Example: One Pass of Compare-and-Swap
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
Step 1 — Read the loop. It compares each neighbor pair from left to right and swaps any pair that is out of order. The bound arr.length - 1 keeps i + 1 inside the array.
Step 2 — Trace {5, 1, 4, 2, 8}.
| i | Compare | Swap? | Array afterward |
|---|---|---|---|
| 0 | 5 > 1 | yes | {1, 5, 4, 2, 8} |
| 1 | 5 > 4 | yes | {1, 4, 5, 2, 8} |
| 2 | 5 > 2 | yes | {1, 4, 2, 5, 8} |
| 3 | 5 > 8 | no | {1, 4, 2, 5, 8} |
Step 3 — Notice what moved. The 5 was carried right until it met a larger value, and then the 8 stayed at the end. A single pass always leaves the largest value in the last position, but it does not sort the array: 4 and 2 are still out of order.
Step 4 — Count. The pass made 4 comparisons and 3 swaps. A second pass on {1, 4, 2, 5, 8} makes one more swap and produces {1, 2, 4, 5, 8}.
AP-Style Application 🎯
Use the compare-and-swap loop from the worked example.
Part 4: Searching: Linear Search Variants and Binary Search
📊 Array Algorithms
Part 4 of 7 — Searching: Linear Search Variants and Binary Search
Part 1 wrote the basic linear search: check each element from the front and return the first matching index, or -1. This part covers the variations the exam uses (CED Topic 4.14) and then a much faster search for sorted data, binary search (CED Topic 4.17).
| In this part |
|---|
| Searching from the back, and searching with a while loop |
| Searching arrays of String and arrays of objects |
| Binary search: the code and a full trace |
| Counting the elements each search examines |
| When binary search gives a wrong answer |
Linear Search Variants
The Last Occurrence: Search Backward
public static int lastIndexOf(int[] arr, int target) {
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
With int[] w = {12, 5, 9, 5, 30, 7};, here is what each search returns and how many elements it compares:
| target | First index (comparisons) | Last index (comparisons) |
|---|---|---|
| 5 | 1 (2) | 3 (3) |
| 30 | 4 (5) | 4 (2) |
| 8 | -1 (6) | -1 (6) |
A search that finds its target at the k-th element it checks makes k comparisons. A search for a missing value checks all n elements.
Searching with a while Loop
int i = 0;
while (i < arr.length && arr[i] != target) {
i++;
}
// now i is the first matching index, or arr.length if there is no match
The loop stops for one of two reasons, so the code after it must check which: i < arr.length means the target was found at index i. The order of the two tests matters. With arr[i] != target && i < arr.length, a missing target drives i to arr.length, and arr[i] is evaluated before the bounds test, throwing an ArrayIndexOutOfBoundsException. In the correct order, short-circuit evaluation skips arr[i] once i < arr.length is false.
Arrays of String
public static int find(String[] names, String target) {
for (int i = 0; i < names.length; i++) {
if (names[i].equals(target)) {
return i;
}
}
return -1;
}
Use equals, not ==. The == operator checks whether two variables refer to the same object, so two separate String objects with the same letters can compare as not equal.
Arrays of Objects: Search by an Accessor
Assume a Book class with a getTitle() method.
public static Book findByTitle(Book[] shelf, String title) {
for (Book b : shelf) {
if (b.getTitle().equals(title)) {
return b;
}
}
return null;
}
The method returns the matching object, or null if there is none. Code that calls it must check for null before calling a method on the result, or it risks a NullPointerException.
🎯 AP Connection: Free-response questions often search a collection of objects using an accessor such as
getName()orgetScore(). The pattern is the same for an array and for a list: compare String results withequalsand number results with==.
Concept Check 🎯
Use int[] w = {12, 5, 9, 5, 30, 7}; and the code above.
Binary Search
Binary search works only on an array that is sorted. It checks the middle element and, depending on the result, throws away the half of the remaining range that cannot contain the target.
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1; // target can only be to the right
} else {
high = mid - 1; // target can only be to the left
}
}
return -1;
}
(low + high) / 2 is int division, so the middle of an even-sized range rounds down. The updates mid + 1 and mid - 1 drop arr[mid] itself, because it has already been checked.
Trace 1: A Target That Is Present
int[] d = {3, 8, 12, 17, 21, 26, 30, 35, 41, 47, 52}; (indexes 0 to 10), searching for 35:
| Pass | low | high | mid | d[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 10 | 5 | 26 | 26 < 35, so low = 6 |
| 2 | 6 | 10 | 8 | 41 | 41 > 35, so high = 7 |
| 3 | 6 | 7 | 6 | 30 | 30 < 35, so low = 7 |
| 4 | 7 | 7 | 7 | 35 | found: return 7 |
Midpoints visited: 5, 8, 6, 7.
Trace 2: A Target That Is Missing
Searching the same array for 10:
| Pass | low | high | mid | d[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 10 | 5 | 26 | 26 > 10, so high = 4 |
| 2 | 0 | 4 | 2 | 12 | 12 > 10, so high = 1 |
| 3 | 0 | 1 | 0 | 3 | 3 < 10, so low = 1 |
| 4 | 1 | 1 | 1 | 8 | 8 < 10, so low = 2 |
| — | 2 | 1 | — | — | low > high: the loop ends and the method returns -1 |
Midpoints visited: 5, 2, 0, 1. The loop ends when low passes high, which means the range that could hold the target is empty. At that moment low is the index where 10 would be inserted to keep the array sorted.
Trace the Midpoints 🔍
Use the sorted array d from the traces above.
How Many Elements Does Each Search Examine?
Each binary search pass examines one element and at least halves the range that is left. Linear search examines elements one at a time.
Search in d (11 elements) | Linear search examines | Binary search examines |
|---|---|---|
| 26 (index 5) | 6 | 1 |
| 35 (index 7) | 8 | 4 |
| 10 (missing) | 11 | 4 |
The largest number of passes binary search can need grows very slowly:
| Array length n | Linear search, worst case | Binary search, worst case |
|---|---|---|
| 7 | 7 | 3 |
| 15 | 15 | 4 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
Doubling the length adds only one pass to binary search's worst case, while it doubles linear search's.
When Binary Search Goes Wrong
| Situation | What happens | Example |
|---|---|---|
| Array not sorted | it can miss a value that is present | {9, 2, 7, 4, 5} searched for 9: midpoints 2, 3, 4, then -1, although 9 is at index 0 |
| Repeated values | it returns an index of the target, not necessarily the first | {2, 4, 4, 4, 9} searched for 4 returns 2, not 1 |
low = mid instead of mid + 1 | the range can stop shrinking, so the loop never ends | in d, searching for 52 gets stuck with low 9 and high 10 |
Condition low < high | a one-element range is never checked | the last remaining candidate is skipped |
Binary Search on Strings
A sorted array of String is searched the same way, using compareTo in place of < and >:
int cmp = words[mid].compareTo(target);
if (cmp == 0) {
return mid;
} else if (cmp < 0) {
low = mid + 1; // words[mid] comes before target
} else {
high = mid - 1;
}
In {"ant", "bee", "cat", "dog", "eel", "fox", "gnu"}, a search for "eel" examines "dog" (index 3), "fox" (index 5) and then "eel" (index 4).
🎯 AP Connection: Exam questions ask which elements binary search examines, how many passes it makes, or what it returns for a missing value. Compute every midpoint with int division, and update low and high with mid + 1 and mid - 1 exactly as the code says.
AP-Style Application 🎯
int[] e = {4, 9, 15, 22, 28, 33, 40, 46, 51}; is searched with the binarySearch method.
Part 5: Sorting and Recursion: Selection, Insertion, Merge Sort
📊 Array Algorithms
Part 5 of 7 — Sorting and Recursion: Selection, Insertion, Merge Sort
This part covers the three sorting algorithms in the course and the idea that two of the search and sort algorithms depend on: recursion.
| CED topic | In this part |
|---|---|
| 4.15 Sorting algorithms | selection sort pass by pass, insertion sort code and trace, comparison counts |
| 4.16 Recursion | base case and recursive call, tracing calls and return values |
| 4.17 Recursive searching and sorting | merge sort, recursive binary search |
🔑 Key Concept: On the exam you trace these algorithms: predict the array after a given pass, count comparisons, or follow recursive calls. You are not asked to write merge sort or other recursive code from scratch.
Selection Sort, Pass by Pass
Part 1 showed the code. Each pass i finds the smallest value in arr[i] through the end and swaps it into position i. Tracing {29, 10, 14, 37, 13}:
| Pass (i) | Smallest in the unsorted part | Swap | Array after the pass |
|---|---|---|---|
| 0 | 10 at index 1 | indexes 0 and 1 | {10, 29, 14, 37, 13} |
| 1 | 13 at index 4 | indexes 1 and 4 | {10, 13, 14, 37, 29} |
| 2 | 14 at index 2 | with itself | {10, 13, 14, 37, 29} |
| 3 | 29 at index 4 | indexes 3 and 4 | {10, 13, 14, 29, 37} |
After pass i, positions 0 through i hold the smallest values in the whole array, in their final places. The inner loop makes 4 + 3 + 2 + 1 = 10 comparisons no matter how the data starts.
Insertion Sort
Insertion sort keeps a sorted section at the front. Each pass takes the next element, shifts every larger element in the sorted section one place right, and drops the element into the gap.
public static void insertionSort(int[] arr) {
for (int j = 1; j < arr.length; j++) {
int temp = arr[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp < arr[possibleIndex - 1]) {
arr[possibleIndex] = arr[possibleIndex - 1];
possibleIndex--;
}
arr[possibleIndex] = temp;
}
}
Tracing {29, 10, 14, 37, 13}. A comparison is one evaluation of temp < arr[possibleIndex - 1].
| Pass (j) | temp | Shifted right | temp placed at | Array after the pass | Comparisons |
|---|---|---|---|---|---|
| 1 | 10 | 29 | index 0 | {10, 29, 14, 37, 13} | 1 |
| 2 | 14 | 29 | index 1 | {10, 14, 29, 37, 13} | 2 |
| 3 | 37 | nothing | index 3 | {10, 14, 29, 37, 13} | 1 |
| 4 | 13 | 37, 29, 14 | index 1 | {10, 13, 14, 29, 37} | 4 |
In pass 1, after 29 shifts, possibleIndex is 0, so possibleIndex > 0 is false and short-circuit evaluation skips the comparison that would read arr[-1]. The total is 8 comparisons.
Comparing the Two Sorts
| Data | Selection sort comparisons | Insertion sort comparisons |
|---|---|---|
{1, 2, 3, 4, 5} (already sorted) | 10 | 4 |
{5, 4, 3, 2, 1} (reverse order) | 10 | 10 |
{29, 10, 14, 37, 13} | 10 | 8 |
| 10 values, already sorted | 45 | 9 |
| 10 values, reverse order | 45 | 45 |
Selection sort always scans the whole unsorted part, so its count depends only on the length. Insertion sort stops each pass as soon as temp finds its place, so nearly sorted data makes it fast and reverse-ordered data is its worst case.
🎯 AP Connection: To tell the sorts apart from a partly sorted array: after k passes, selection sort's front holds the k smallest values of the whole array, while insertion sort's front holds the first k + 1 original values in sorted order.
Concept Check 🎯
The array {7, 2, 9, 4, 5} is sorted in increasing order.
Recursion: A Method That Calls Itself
A recursive method is a method that calls itself (CED Topic 4.16). Every recursive method needs two parts:
| Part | Job |
|---|---|
| Base case | an input simple enough to answer directly, with no recursive call |
| Recursive call | a call on a smaller or simpler version of the problem, moving toward the base case |
Without a base case, or with a call that never moves toward it, the calls never stop. This is infinite recursion, and the program crashes with a StackOverflowError. Any recursive method can also be written with a loop.
Example 1: Sum of an Array from Index i
public static int sum(int[] arr, int i) {
if (i == arr.length) {
return 0; // base case: no elements left
}
return arr[i] + sum(arr, i + 1); // this element plus the rest
}
Calling sum(arr, 0) with arr = {4, 7, 2}:
| Call | i | Returns |
|---|---|---|
sum(arr, 0) | 0 | 4 + sum(arr, 1) = 4 + 9 = 13 |
sum(arr, 1) | 1 | 7 + sum(arr, 2) = 7 + 2 = 9 |
sum(arr, 2) | 2 | 2 + sum(arr, 3) = 2 + 0 = 2 |
sum(arr, 3) | 3 | 0 (base case) |
Read the table down to see the calls being made and up to see the values coming back. Each call has its own copy of the parameter i, so four different i values exist at the deepest point. A 3-element array takes 4 calls, one more than its length.
Example 2: Work Before and After the Call
public static void echo(int n) {
if (n > 0) {
System.out.print(n + " ");
echo(n - 1);
System.out.print(n + " ");
}
}
echo(3) prints 3 2 1 1 2 3 . The base case is n = 0, which does nothing. The first print runs on the way down, as each call starts (3, 2, 1). The second print waits until the call it follows has completely finished, so it runs on the way back up, deepest call first (1, 2, 3).
Example 3: Recursion on a String
public static String reverse(String s) {
if (s.length() <= 1) {
return s;
}
return reverse(s.substring(1)) + s.substring(0, 1);
}
reverse("code") calls reverse("ode"), which calls reverse("de"), which calls reverse("e"), the base case. The returns build the answer from the inside out: "e", then "e" + "d" = "ed", then "ed" + "o" = "edo", and finally "edo" + "c" = "edoc".
Trace the Recursion ✍️
public static int digitSum(int n) {
if (n < 10) {
return n;
}
return digitSum(n / 10) + n % 10;
}
public static int f(int n) {
if (n <= 1) {
return 1;
}
return n * f(n - 2);
}
-
What does
digitSum(375)return? _______ -
What does
f(7)return? _______ -
For an array of 5 elements, how many calls to
sum, including the first, doessum(arr, 0)make? _______
Merge Sort
Merge sort is a recursive sorting algorithm (CED Topic 4.17):
- If the range has one element, it is already sorted (the base case).
- Otherwise, split the range in half and merge sort each half (two recursive calls).
- Merge the two sorted halves into one sorted range.
public static void mergeSort(int[] arr) {
int[] temp = new int[arr.length];
mergeSortHelper(arr, 0, arr.length - 1, temp);
}
private static void mergeSortHelper(int[] arr, int from, int to, int[] temp) {
if (from < to) {
int middle = (from + to) / 2;
mergeSortHelper(arr, from, middle, temp);
mergeSortHelper(arr, middle + 1, to, temp);
merge(arr, from, middle, to, temp);
}
}
The merge method (not shown) repeatedly compares the front values of the two sorted halves, copies the smaller one into temp, then copies any leftovers and finally copies temp back into arr.
The Merge Step
Merging the sorted halves {2, 5, 6, 8} and {1, 3, 7, 9}:
| Fronts compared | Taken | Merged so far |
|---|---|---|
| 2 and 1 | 1 | 1 |
| 2 and 3 | 2 | 1 2 |
| 5 and 3 | 3 | 1 2 3 |
| 5 and 7 | 5 | 1 2 3 5 |
| 6 and 7 | 6 | 1 2 3 5 6 |
| 8 and 7 | 7 | 1 2 3 5 6 7 |
| 8 and 9 | 8 | 1 2 3 5 6 7 8 |
| left half is empty | 9 | 1 2 3 5 6 7 8 9 |
That merge makes 7 comparisons. Because each half is already sorted, the smallest remaining value is always at one of the two fronts.
Array States for {5, 2, 8, 6, 1, 9, 3, 7}
| Merge | Halves merged (index ranges) | Array afterward |
|---|---|---|
| 1 | 0 to 0 with 1 to 1 | {2, 5, 8, 6, 1, 9, 3, 7} |
| 2 | 2 to 2 with 3 to 3 | {2, 5, 6, 8, 1, 9, 3, 7} |
| 3 | 0 to 1 with 2 to 3 | {2, 5, 6, 8, 1, 9, 3, 7} |
| 4 | 4 to 4 with 5 to 5 | {2, 5, 6, 8, 1, 9, 3, 7} |
| 5 | 6 to 6 with 7 to 7 | {2, 5, 6, 8, 1, 9, 3, 7} |
| 6 | 4 to 5 with 6 to 7 | {2, 5, 6, 8, 1, 3, 7, 9} |
| 7 | 0 to 3 with 4 to 7 | {1, 2, 3, 5, 6, 7, 8, 9} |
The left half is completely sorted before any work happens on the right half, because the first recursive call must finish before the second one starts. Some merges change nothing when the halves are already in order. On large arrays that are not already nearly sorted, merge sort makes far fewer comparisons than selection or insertion sort, at the cost of the extra temp array.
Recursive Binary Search
public static int binarySearch(int[] arr, int target, int low, int high) {
if (low > high) {
return -1; // base case: empty range
}
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid; // base case: found
} else if (target < arr[mid]) {
return binarySearch(arr, target, low, mid - 1);
} else {
return binarySearch(arr, target, mid + 1, high);
}
}
The first call is binarySearch(arr, target, 0, arr.length - 1). Each recursive call replaces one pass of the while loop from Part 4, so it visits exactly the same midpoints. With d = {3, 8, 12, 17, 21, 26, 30, 35, 41, 47, 52}:
| Target | Calls (low, high) | Midpoints | Returns |
|---|---|---|---|
| 47 | (0, 10), (6, 10), (9, 10) | 5, 8, 9 | 9 |
| 20 | (0, 10), (0, 4), (3, 4), (4, 4), (4, 3) | 5, 2, 3, 4 | -1 |
The found index is returned by the deepest call and passed back unchanged by every call above it, because each one says return binarySearch(...).
AP-Style Application 🎯
Part 6: AP-Style Practice
📊 Array Algorithms
Part 6 of 7 — AP-Style Practice
Array algorithms appear in multiple-choice questions as traces ("what does the array contain afterward?") and counts ("how many elements are examined?"). The free-response section has no question devoted to one-dimensional arrays alone, but the same traversal patterns (total, count, extreme, search, any/all) are the building blocks of question 3 (data analysis with a list) and question 4 (two-dimensional arrays). This part practices tracing and writing these methods, using only the Java Quick Reference subset.
How to Attack an Array Question
| Step | Do this |
|---|---|
| 1 | Write the array with its indexes underneath. Most errors are index errors. |
| 2 | Find the loop's first and last index, and check whether i + 1 or i - 1 stays inside 0 to length - 1. |
| 3 | When an assignment overwrites an element, redraw the array after each pass. |
| 4 | For search and sort counts, list each comparison rather than estimating. |
| 5 | For recursion, write each call with its own parameter values, then fill in the returns from the bottom up. |
🔑 Key Concept: A rearranging loop changes the array while it reads it. Trace with the current contents, not the original ones.
Practice Set 1: Tracing 🎯
Segment A
int[] arr = {3, 6, 1, 8, 2};
int m = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[m]) {
m = i;
}
}
int temp = arr[0];
arr[0] = arr[m];
arr[m] = temp;
Segment B
int[] vals = {2, 7, 7, 3, 7, 1};
int count = 0;
for (int i = 0; i < vals.length; i++) {
for (int j = i + 1; j < vals.length; j++) {
if (vals[i] == vals[j]) {
count++;
}
}
}
System.out.println(count);
Segment C
int[] nums = {1, 2, 3, 4, 5, 6};
int half = nums.length / 2;
for (int i = 0; i < half; i++) {
int temp = nums[i];
nums[i] = nums[i + half];
nums[i + half] = temp;
}
FRQ-Style Task 1 — isSorted and countRuns
Part (a): isSorted
Prompt. Return true if every element of arr is less than or equal to the element after it, and false otherwise.
public static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
| Call | Returns | Comparisons |
|---|---|---|
isSorted({2, 4, 4, 9}) | true | 3 |
isSorted({1, 3, 2, 5}) | false | 2 |
isSorted({7}) | true | 0 |
This is the "all" pattern from Part 2: one out-of-order neighbor pair is a counterexample, and true is returned only after every pair has passed. Equal neighbors are allowed, so the test is >, not >=.
Part (b): countRuns
Prompt. A run is a block of two or more adjacent equal values that cannot be made longer. Return the number of runs in arr.
| Call | Runs | Returns |
|---|---|---|
countRuns({1, 1, 2, 3, 3, 3, 4, 1, 1}) | 1 1, then 3 3 3, then 1 1 | 3 |
countRuns({5, 5, 5, 5}) | 5 5 5 5 | 1 |
countRuns({1, 2, 3}) | none | 0 |
countRuns({4, 4, 1, 4, 4}) | 4 4, then 4 4 | 2 |
Plan. Count each run once, at the position where it starts: index i starts a run when arr[i] equals arr[i + 1] and either i is 0 or arr[i - 1] is different.
public static int countRuns(int[] arr) {
int runs = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] == arr[i + 1] && (i == 0 || arr[i - 1] != arr[i])) {
runs++;
}
}
return runs;
}
The test i == 0 comes first so that short-circuit evaluation skips arr[i - 1] when i is 0.
What a Rubric Looks For
| Point | Earned by |
|---|---|
| Traversal | visits every neighbor pair without going out of bounds |
| Comparison | compares arr[i] with arr[i + 1] using the correct operator |
| Logic | returns false at the first counterexample (a) / counts each run exactly once (b) |
| Result | returns the boolean or count after the loop, rather than printing it |
Practice Set 2: Reasoning About the Solutions 🎯
FRQ-Style Task 2 — rotateRight
Prompt. Return a new array in which every element of arr has moved k positions to the right, with elements that pass the end wrapping around to the front. Assume k is at least 0 and arr is not changed.
| Call | Returns |
|---|---|
rotateRight({1, 2, 3, 4, 5}, 2) | {4, 5, 1, 2, 3} |
rotateRight({1, 2, 3, 4, 5}, 5) | {1, 2, 3, 4, 5} |
rotateRight({1, 2, 3, 4, 5}, 0) | {1, 2, 3, 4, 5} |
rotateRight({6, 7, 8}, 4) | {8, 6, 7} |
Solution
public static int[] rotateRight(int[] arr, int k) {
int n = arr.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[(i + k) % n] = arr[i];
}
return result;
}
- The new position is
(i + k) % n. The remainder wraps any position pastn - 1back to the front, so k = 5 on 5 elements, and k = 4 on 3 elements, work without any special case. - Each element is written exactly once. Because the result is a separate array, no value is overwritten before it is read, so no temp variable is needed.
- The direction is in the subscript. Writing
result[i] = arr[(i + k) % n]instead moves every element k places left:{1, 2, 3, 4, 5}with k = 2 becomes{3, 4, 5, 1, 2}.
An In-Place Alternative
Calling the Part 3 rotateRight(arr) method k times also works, but it changes the original array and moves every element k separate times.
Applied Recall ✍️
-
What does
countRuns({3, 3, 3, 8, 8, 1, 9, 9})return? _______ -
How many times does
isSortedevaluatearr[i] > arr[i + 1]for{2, 5, 9, 4, 10}? _______ -
For
rotateRight({4, 8, 15, 16, 23, 42}, 2), what value is at index 0 of the returned array? _______
Common FRQ Deductions on Array Algorithms
| Mistake | Why it costs points |
|---|---|
Loop bound i < arr.length while reading arr[i + 1] | the last pass reads past the end of the array |
| Returning inside the loop on both branches | the method decides after looking at one element |
| Starting a maximum or minimum at 0 | wrong for arrays whose values are all negative, or all positive |
| Shifting right with a forward loop | one value is copied into every slot |
| Using the same index for the old array and a shorter new one | skips slots or throws an exception |
Comparing Strings or objects with == | compares references, not contents |
| Printing the answer instead of returning it | the method must return a value to its caller |
🎯 AP Connection: Before writing any array loop, write down three things: the first index, the last index, and every index expression in the body. If the body uses
i + 1, the last i must bearr.length - 2.
Part 7: Synthesis Review
📊 Array Algorithms
Part 7 of 7 — Synthesis Review
This part ties the topic together: the standard array algorithms (CED Topic 4.5), searching (4.14 and 4.17), sorting (4.15 and 4.17) and recursion (4.16). Use the table as a checklist, then test yourself on mixed questions.
The Topic on One Page
| Algorithm | Key fact | Typical trap |
|---|---|---|
| Sum and average (Part 2) | cast before dividing: (double) sum / arr.length | int division drops the fraction |
| Max or min with index (Part 2) | start from arr[0]; > keeps the first tie | starting at 0 |
| Any / all (Part 2) | return inside the loop for the deciding case, the default after it | an else branch that returns early |
| Duplicates (Part 2) | inner loop starts at i + 1 | comparing an element with itself |
| Rotations and shifts (Part 3) | save the value that falls off; shift right with a backward loop | a forward loop copies one value everywhere |
| Compaction and filtering (Part 3) | a second index for the destination | reusing the source index |
| Linear search (Part 4) | works on any data; equals for Strings | swapping the operands of the while test |
| Binary search (Parts 4 and 5) | sorted data only; mid = (low + high) / 2, then mid + 1 or mid - 1 | forgetting int division rounds down |
| Selection sort (Part 5) | front holds the smallest values in final places; same comparisons for any order | thinking sorted input saves work |
| Insertion sort (Part 5) | front holds the first values sorted; fast on nearly sorted data | confusing its passes with selection sort's |
| Recursion and merge sort (Part 5) | base case plus a call that moves toward it; split, sort halves, merge | missing or unreachable base case |
Worked Example: One Array, Four Algorithms
int[] data = {14, 3, 9, 3, 20, 6};
Step 1 — Minimum with index. Starting from index 0 and testing data[i] < data[minIndex], the index moves to 1 (value 3) and stays there: the 3 at index 3 only ties, and < keeps the first one. Result: index 1.
Step 2 — Frequency of the minimum. countOf(data, 3) returns 2.
Step 3 — Insertion sort.
| Pass (j) | temp | Array after the pass |
|---|---|---|
| 1 | 3 | {3, 14, 9, 3, 20, 6} |
| 2 | 9 | {3, 9, 14, 3, 20, 6} |
| 3 | 3 | {3, 3, 9, 14, 20, 6} |
| 4 | 20 | {3, 3, 9, 14, 20, 6} |
| 5 | 6 | {3, 3, 6, 9, 14, 20} |
Insertion sort makes 11 comparisons here. Selection sort on the same six values would make 5 + 4 + 3 + 2 + 1 = 15. In pass 3 the second 3 stops behind the first one, because 3 < 3 is false.
Step 4 — Binary search on the sorted array. Searching {3, 3, 6, 9, 14, 20} for 20: mid = 2 (value 6), then low = 3 and mid = 4 (value 14), then low = 5 and mid = 5 (value 20). It returns 5 after examining 3 elements. Searching for 9 visits midpoints 2, 4 and 3 and returns 3.
Mixed Review 1 🎯
Segment A
int[] a = {5, 3, 8, 1};
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
Segment B
int[] b = {2, 9, 4, 7, 6};
int total = 0;
for (int i = b.length - 1; i >= 0; i -= 2) {
total += b[i];
}
Method C
public static int countEven(int[] arr, int i) {
if (i < 0) {
return 0;
}
if (arr[i] % 2 == 0) {
return 1 + countEven(arr, i - 1);
}
return countEven(arr, i - 1);
}
Count Reference
| Algorithm | Comparisons or passes for n elements |
|---|---|
| Linear search | k for a target found at the k-th element checked; n when the target is missing |
| Binary search | at most 3 for n = 7, 4 for 15, 7 for 100, 10 for 1,000 |
| Selection sort | (n - 1) + (n - 2) + ... + 1 = n(n - 1) / 2, for any starting order |
| Insertion sort | n - 1 when already sorted; n(n - 1) / 2 when in reverse order |
| Duplicate check, every pair | up to n(n - 1) / 2; fewer when a duplicate is found early |
| Recursive sum from index 0 | n + 1 calls |
Error Catalogue
| Symptom | Likely cause | Fix |
|---|---|---|
| ArrayIndexOutOfBoundsException on the last pass | the body uses i + 1 with i < arr.length | stop at arr.length - 1 |
| one value fills the whole array | shifting right with a forward loop | loop backward |
| average is a whole number | int division | cast to double before dividing |
| any/all method answers from the first element | return in both branches inside the loop | return the default after the loop |
| binary search misses a present value | the array is not sorted, or the low/high updates are wrong | sort first; use mid + 1 and mid - 1 |
| StackOverflowError | no base case, or the recursive call does not move toward it | add or fix the base case |
🎯 AP Connection: When two answer choices differ only at one index, retrace that single index carefully. Exam distractors are built from the off-by-one, wrong-direction and missing-save mistakes in this table.
Quick Evaluation 🔍
Mixed Review 2 🎯