AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/4/4-5)
Unit 4 · Topic 4.5
4.5 Implementing Array Algorithms
Most array questions are variations on a short list of standard algorithms: min and max, sum and average, any and all, counting, consecutive pairs, duplicates, shifting, rotating and reversing. Learn the pattern for each and you can adapt it to almost any problem.
Key terms
- min and max
- sum and average
- count
- consecutive pairs
- duplicates
- shift, rotate and reverse
One traversal, one tracking variable
Most of these are a single traversal with the right variable to track the answer. Pick the variable's starting value carefully, because that's where most bugs come from.
- Min or max: start with
data[0]and replace it whenever you see something smaller (or larger). - Sum or average: add every element to a running total, then divide by
length, casting todoubleif needed. - Count: add 1 to a counter when an element meets the condition.
- At least one: return
trueas soon as an element meets the condition, andfalseafter the loop. - All: return
falseas soon as an element fails, andtrueafter the loop. - Consecutive pairs: loop
ifrom 0 tolength - 2and comparedata[i]withdata[i + 1]. - Duplicates: compare every pair with nested loops, starting the inner index at
i + 1(2.11).
Checking all elements
"All" and "at least one" are mirror images. For "all", one failure is enough to answer false:
public static boolean allPositive(int[] data)
{
for (int value : data)
{
if (value <= 0)
{
return false;
}
}
return true;
}
Shifting and rotating
To rotate left by one, save the first element, shift every other element one place left, then put the saved value at the end. Shifting right is the mirror image, but loop from the end backward, or you'll copy the same value into every slot. A shift that doesn't wrap around just fills the empty end with something else, like 0.
Reversing
To reverse in place, swap the first and last elements, then the second and second-to-last, and so on, stopping at the middle. The partner of index i is arr.length - 1 - i. A swap needs a temporary variable, or you'll lose one of the values.
int[] arr = {8, 6, 7, 5, 3};
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;
}
This turns 8, 6, 7, 5, 3 into 3, 5, 7, 6, 8. The loop runs arr.length / 2 times, so for odd lengths the middle element stays put. Looping all the way to arr.length would swap everything twice and put it back the way it was.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Write a method: range of the data
Write a method
range(int[] data)that returns the difference between the largest and smallest values.datahas at least one element. One solution:public static int range(int[] data) { int low = data[0]; int high = data[0]; for (int value : data) { if (value < low) { low = value; } if (value > high) { high = value; } } return high - low; }Show the solutionHide the solution
- Step 1: This combines min and max in one traversal.
- Step 2: Start both
lowandhighatdata[0], a real value, not 0. With the data -4, -9, -2, -7, ahighthat started at 0 would never change and give the wrong answer. - Step 3: For -4, -9, -2, -7:
lowends at -9 andhighat -2, so the range is -2 − (-9) = 7. - Step 4: For a one-element array like {5}, both are 5 and the range is 0.
Answer: The method above; it returns 7 for {-4, -9, -2, -7} and 0 for {5}.
- Example 2
Rotating left
What does this code print?
int[] arr = {1, 2, 3, 4, 5}; int first = arr[0]; for (int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i + 1]; } arr[arr.length - 1] = first; for (int v : arr) { System.out.print(v + " "); } System.out.println();Show the solutionHide the solution
- Step 1: Save
first= 1. - Step 2: The loop runs for
i= 0 to 3 and copies each element from the right:arr[0]= 2,arr[1]= 3,arr[2]= 4,arr[3]= 5. Stopping atlength - 1keepsarr[i + 1]in bounds. - Step 3: Then the saved 1 goes into the last slot.
Answer: It prints
2 3 4 5 1. - Step 1: Save
- Example 3
Consecutive pairs
This counts the days where the step count went up from the day before. What does it print?
int[] steps = {4000, 6500, 6100, 8000}; int increases = 0; for (int i = 0; i < steps.length - 1; i++) { if (steps[i + 1] > steps[i]) { increases++; } } System.out.println(increases);Show the solutionHide the solution
- Step 1: Pairs are (4000, 6500), (6500, 6100) and (6100, 8000). The loop stops at
i= 2 soi + 1is at most 3. - Step 2: Up, down, up: 2 increases.
Answer: It prints
2. - Step 1: Pairs are (4000, 6500), (6500, 6100) and (6100, 8000). The loop stops at
Common mistakes
- Starting a max at 0 or a min at 0. Start with
data[0]. - Looping to
i < arr.lengthwhile usingarr[i + 1], which goes out of bounds on the last pass. - Returning
truefrom an "all" check inside the loop after just one element passes. - Swapping without a temporary variable, or reversing all the way to the end, which undoes the swaps.
On the exam
- These same patterns are what free-response Questions 3 and 4 are built on, using an
ArrayListor a 2D array instead of a plain array. Name the pattern, then adjust it.
Connected topics
Videos
Check yourself
4 questions on 4.5 Implementing Array Algorithms. Pick an answer to see if you got it, and why.
The following method is intended to return the largest value in arr./** Precondition: arr.length > 0 */
public static int findMax(int[] arr)
{
/* missing code */
for (int v : arr)
{
if (v > max)
{
max = v;
}
}
return max;
}Which of the following can replace /* missing code */ so that the method works for every array that meets the precondition?
The following method is intended to return true if every element of arr is positive and false otherwise.public static boolean allPositive(int[] arr)
{
/* missing code */
}Which of the following can replace /* missing code */ so that the method works as intended?
Consider the following code segment.int[] a = {3, 5, 5, 2, 8, 9};
int ups = 0;
for (int i = 1; i < a.length; i++)
{
if (a[i] > a[i - 1])
{
ups++;
}
}
System.out.println(ups);What is printed as a result of executing the code segment?
Consider the following method.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;
}Which of the following describes why the inner loop starts at i + 1 rather than at 0?
0 of 4 answered