AP Computer Science A · Study guide

Array Algorithms

AP® Computer Science A · Data Collections

Standard Array Algorithms

The traversal patterns used again and again with arrays: minimum and maximum, sum and average, at-least-one and all, counting, consecutive pairs, duplicates, shifting and rotating, and reversing.

Big Picture

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, and reverse the order of the elements. Each is a small pattern built on a traversal; recognizing which pattern a problem needs is most of the work.

1Minimum, Maximum, Sum, and Average

To determine a minimum or maximum value, keep the best value so far, initialized to the first element, and compare every remaining element with it. Starting with the first element, rather than 0, makes the algorithm correct for any values, including all-negative arrays. To report where the extreme occurs, store its index alongside its value.

To compute a sum, add every element to an accumulator that starts at 0. An average is the sum divided by the number of elements, a.length; for an int array, cast to double before dividing so the fractional part is kept. Both of these algorithms read every element and change nothing, so an enhanced for loop fits naturally.

Standard algorithmKey ideaTypical loop
Minimum or maximumBest so far, starting with the first elementAny traversal from index 1
Sum or averageAccumulate; divide by length as doubleEnhanced for
At least one / all have a propertyReturn early on the deciding elementEnhanced for in a method
Count with a propertyCounter inside an ifEnhanced for
Consecutive pairsa[i] with a[i + 1]Indexed, i < length − 1
DuplicatesCompare every pair onceNested indexed loops, j from i + 1
Shift or rotateSave the overwritten value; move each elementIndexed, direction matters
ReverseSwap a[i] with a[length − 1 − i]Indexed, i < length / 2
Worked Example 1 Minimum and maximum

Both Extremes in One Pass

Predict the output.

Code
int[] a = {14, -3, 22, 7, -9, 18};
int min = a[0];
int max = a[0];
for (int i = 1; i < a.length; i++)
{
    if (a[i] < min)
    {
        min = a[i];
    }
    if (a[i] > max)
    {
        max = a[i];
    }
}
System.out.println(min + " " + max);
Output
-9 22
  1. 1Start with the first element for both trackers, so negative values are handled correctly.
  2. 2Compare from index 1 onward; two separate if statements update each tracker independently.
Result: The output is -9 22. Determining a minimum or maximum keeps the best value so far and replaces it whenever a better one appears.
Worked Example 2 Sum and average

Averaging an Array

Predict the output.

Code
double[] times = {12.5, 11.0, 13.25, 12.25};
double sum = 0.0;
for (double t : times)
{
    sum += t;
}
System.out.println(sum);
System.out.println(sum / times.length);
Output
49.0
12.25
  1. 1Sum. 12.5 + 11.0 + 13.25 + 12.25 = 49.0.
  2. 2Average. Divide by times.length, 4: 12.25.
  3. 3Types. With an int array, cast before dividing: (double) sum / a.length.
Result: The output is 49.0 and 12.25. Computing a sum or average visits every element once, accumulating as it goes.

2Properties of Elements: Any, All, How Many

Three related questions ask about a property, such as being negative or passing. At least one: as soon as one element has the property, the answer is true; the answer is false only after every element has been checked. All: as soon as one element lacks the property, the answer is false; it is true only after every element passes. How many: a counter increases each time the property holds.

Written as methods, "at least one" and "all" can return early from inside the loop, using the return rule that a return exits the method immediately. The final return after the loop handles the case where no element settled the answer. Placing that final return inside the loop, in an else, is the classic error: it decides after looking at only the first element.

ArrayanyNegativeallAtLeast(…, 10)hasDuplicate
{14, 18, 12}falsetruefalse
{14, -3, 12}truefalsefalse
{5, 2, 8, 2}falsefalsetrue
Worked Example 3 At least one, and all

Testing a Property Across the Array

Write anyNegative and allAtLeast, then test them.

Code
public static boolean anyNegative(int[] a)
{
    for (int x : a)
    {
        if (x < 0)
        {
            return true;
        }
    }
    return false;
}

public static boolean allAtLeast(int[] a, int min)
{
    for (int x : a)
    {
        if (x < min)
        {
            return false;
        }
    }
    return true;
}
Output
false true
true false
  1. 1"At least one": return true as soon as one element has the property; only after checking all may the method return false.
  2. 2"All": return false as soon as one element lacks the property; only after checking all may it return true.
  3. 3Results. In p, no value is negative and all are at least 10. In q, −3 is negative, so anyNegative returns true at that element, and allAtLeast returns false at the same element.
Result: The output is false true, then true false. "At least one" and "all" are mirror images: each returns early on the first element that settles the answer.
Worked Example 4 Counting

How Many Elements Have the Property?

Count the passing scores (60 or more).

Code
int[] scores = {72, 58, 91, 60, 45, 88};
int passing = 0;
for (int s : scores)
{
    if (s >= 60)
    {
        passing++;
    }
}
System.out.println(passing + " of " + scores.length);
Output
4 of 6
  1. 1A counter starts at 0 and increases only when the condition holds.
  2. 2Passing: 72, 91, 60, 88. The boundary value 60 counts because of >=.
Result: The output is 4 of 6. Determining the number of elements having a property combines a traversal, an if, and a counter.
Common Mistake 1 · Returning the Default Answer Inside the Loop

In an "at least one" method, writing else { return false; } inside the loop returns after checking only the first element. The return false belongs after the loop, once every element has been examined.

3Consecutive Pairs

Some questions compare neighbors: is each value larger than the one before, how many times does the direction change, are two equal values adjacent? Accessing all consecutive pairs of elements uses an indexed loop that compares a[i] with a[i + 1]. An array of n elements has n - 1 consecutive pairs.

The loop bound must stop one short of the end, i < a.length - 1, so that a[i + 1] is always a valid index. Equivalently, a loop can start at i = 1 and compare a[i - 1] with a[i].

Figure 1. Accessing all consecutive pairs uses an index that stops one short of the last element, so a[i + 1] is always valid.
Worked Example 5 Consecutive pairs

Counting Increases

Count how many times a value is larger than the one before it.

Code
int[] a = {4, 7, 6, 9, 12};
int increases = 0;
for (int i = 0; i < a.length - 1; i++)
{
    if (a[i + 1] > a[i])
    {
        increases++;
    }
}
System.out.println(increases);
Output
3
  1. 1Pairs. (4,7), (7,6), (6,9), (9,12): four pairs for five elements.
  2. 2Bound. i < a.length - 1 keeps a[i + 1] inside the array.
  3. 3Increases: 4→7, 6→9, 9→12: 3.
Result: The output is 3. Accessing all consecutive pairs of elements requires an index and a bound one short of the end.
Common Mistake 2 · Running the Pairs Loop to the End

With i < a.length, the last pass evaluates a[a.length] and throws an ArrayIndexOutOfBoundsException. A pairs loop runs one fewer time than a full traversal.

4Presence or Absence of Duplicates

To determine whether any value appears more than once, compare every pair of elements. Nested loops do this: the outer index i visits each position, and the inner index j visits every later position, starting at i + 1. Each pair is compared exactly once, and no element is compared with itself.

As soon as two equal elements are found, the answer is "duplicates present," and a method can return true immediately. Only after every pair has been compared can it return false. For an array of n elements this takes n(n − 1) / 2 comparisons, which grows quickly for large arrays.

Figure 2. Determining the presence or absence of duplicates compares every pair of elements once, using nested loops with the inner index starting after the outer one.
Worked Example 6 Duplicates

Is Any Value Repeated?

Predict the output.

Code
public static boolean hasDuplicate(int[] a)
{
    for (int i = 0; i < a.length; i++)
    {
        for (int j = i + 1; j < a.length; j++)
        {
            if (a[i] == a[j])
            {
                return true;
            }
        }
    }
    return false;
}
Output
true
false
  1. 1Every pair once. The inner index starts at i + 1, so each pair of positions is compared exactly once, and no element is compared with itself.
  2. 2p has 2 at positions 1 and 3: true. q has no repeats: false.
Result: The output is true, then false. Determining the presence or absence of duplicate elements compares every pair, returning as soon as a match is found.

5Shifting and Rotating

To shift elements left, each element moves to the previous index: a[i] = a[i + 1] for i from 0 up to a.length - 2. To rotate left, the first element, which would otherwise be overwritten and lost, is saved first and placed in the last position afterward. Shifting and rotating right mirror this: each element moves to the next index, and the loop must run backward from the end so that each value is copied before it is overwritten.

The direction of the loop is the subtle part. A forward loop that copies a[i] = a[i - 1] overwrites each value before it has been moved, filling the array with copies of one element. Tracing two or three passes on paper reveals the problem immediately.

Figure 3. Rotating elements left moves each one to the previous index and wraps the first element to the end, using a temporary variable so no value is lost.
Worked Example 7 Shift and rotate

Rotating Left, Then Right

Rotate the array left by one, then rotate it back to the right.

Code
int[] a = {3, 8, 1, 6, 5};
int first = a[0];
for (int i = 0; i < a.length - 1; i++)
{
    a[i] = a[i + 1];
}
a[a.length - 1] = first;
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " + a[4]);
int last = a[a.length - 1];
for (int i = a.length - 1; i > 0; i--)
{
    a[i] = a[i - 1];
}
a[0] = last;
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " + a[4]);
Output
8 1 6 5 3
3 8 1 6 5
  1. 1Rotate left. Save a[0], copy each element from the next position going forward, then put the saved value at the end.
  2. 2Rotate right. Save the last element, copy each element from the previous position going backward, then put the saved value at index 0.
  3. 3Direction of the loop matters. Shifting right with a forward loop would copy the same value into every position.
Result: The output is 8 1 6 5 3, then 3 8 1 6 5. Shifting or rotating elements moves each one to a neighboring index, saving whichever value would otherwise be overwritten.
Common Mistake 3 · Shifting in the Wrong Direction

When shifting right, a forward loop copies a[0] into every position. Run the loop from the end toward the front, so each element is moved before the slot it came from is reused.

6Reversing the Order

To reverse the order of the elements in place, swap the first element with the last, the second with the second-to-last, and so on toward the middle. Element i swaps with element a.length - 1 - i, and each swap needs a temporary variable to hold one value while the other is copied over it.

The loop runs only to the middle, i < a.length / 2. In an array with an odd length, the middle element stays where it is. Running the loop to the end swaps every pair a second time, which undoes the first half of the work and leaves the array unchanged.

Figure 4. Reversing the order of the elements in place swaps pairs from both ends toward the middle; each swap needs a temporary variable.
Worked Example 8 Reverse

Reversing in Place

Reverse the array by swapping.

Code
int[] a = {2, 4, 6, 8, 10};
for (int i = 0; i < a.length / 2; i++)
{
    int temp = a[i];
    a[i] = a[a.length - 1 - i];
    a[a.length - 1 - i] = temp;
}
System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " + a[4]);
Output
10 8 6 4 2
  1. 1Partner index. Element i swaps with a.length - 1 - i: 0 with 4, 1 with 3.
  2. 2Stop halfway. a.length / 2 is 2, so two swaps; going further would swap the pairs back.
  3. 3The temporary variable keeps one value safe while the other is copied over it.
Result: The output is 10 8 6 4 2. Reversing the order of the elements swaps pairs from the two ends toward the middle.
MistakeEffect
Max starts at 0Wrong when all values are negative
Pairs loop uses i < a.lengtha[i + 1] goes out of bounds on the last pass
"At least one" returns false inside the loopDecides after checking only the first element
Reverse loop runs to a.lengthEvery pair is swapped twice: no change
Shift right with a forward loopOne value copied into every position
Common Mistake 4 · Swapping Without a Temporary Variable

a[i] = a[j]; a[j] = a[i]; loses the original a[i], leaving both positions with the same value. Save one value first: int temp = a[i]; a[i] = a[j]; a[j] = temp;.

Four Habits for Array Algorithms

1. Start Extremes With a[0]

Never with 0.

2. Decide Any/All After the Loop

Return early only on the deciding element.

3. Pairs Stop at length − 1

So a[i + 1] stays in bounds.

4. Save Before Overwriting

Rotations and swaps need a temporary variable.

Core Synthesis

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; and reverse the order of the elements. Each depends on careful initialization, the right loop bounds, and, for in-place changes, saving any value that would otherwise be overwritten.