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.
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 algorithm | Key idea | Typical loop |
|---|---|---|
| Minimum or maximum | Best so far, starting with the first element | Any traversal from index 1 |
| Sum or average | Accumulate; divide by length as double | Enhanced for |
| At least one / all have a property | Return early on the deciding element | Enhanced for in a method |
| Count with a property | Counter inside an if | Enhanced for |
| Consecutive pairs | a[i] with a[i + 1] | Indexed, i < length − 1 |
| Duplicates | Compare every pair once | Nested indexed loops, j from i + 1 |
| Shift or rotate | Save the overwritten value; move each element | Indexed, direction matters |
| Reverse | Swap a[i] with a[length − 1 − i] | Indexed, i < length / 2 |
Both Extremes in One Pass
Predict the output.
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);
-9 22
- 1Start with the first element for both trackers, so negative values are handled correctly.
- 2Compare from index 1 onward; two separate
ifstatements update each tracker independently.
Averaging an Array
Predict the output.
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);
49.0
12.25
- 1Sum. 12.5 + 11.0 + 13.25 + 12.25 = 49.0.
- 2Average. Divide by
times.length, 4: 12.25. - 3Types. With an
intarray, cast before dividing:(double) sum / a.length.
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.
| Array | anyNegative | allAtLeast(…, 10) | hasDuplicate |
|---|---|---|---|
| {14, 18, 12} | false | true | false |
| {14, -3, 12} | true | false | false |
| {5, 2, 8, 2} | false | false | true |
Testing a Property Across the Array
Write anyNegative and allAtLeast, then test them.
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;
}
false true
true false
- 1"At least one": return
trueas soon as one element has the property; only after checking all may the method returnfalse. - 2"All": return
falseas soon as one element lacks the property; only after checking all may it returntrue. - 3Results. In
p, no value is negative and all are at least 10. Inq, −3 is negative, soanyNegativereturnstrueat that element, andallAtLeastreturnsfalseat the same element.
How Many Elements Have the Property?
Count the passing scores (60 or more).
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);
4 of 6
- 1A counter starts at 0 and increases only when the condition holds.
- 2Passing: 72, 91, 60, 88. The boundary value 60 counts because of
>=.
if, and a counter.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].
a[i + 1] is always valid.Counting Increases
Count how many times a value is larger than the one before it.
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);
3
- 1Pairs. (4,7), (7,6), (6,9), (9,12): four pairs for five elements.
- 2Bound.
i < a.length - 1keepsa[i + 1]inside the array. - 3Increases: 4→7, 6→9, 9→12: 3.
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.
Is Any Value Repeated?
Predict the output.
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;
}
true
false
- 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
phas 2 at positions 1 and 3:true.qhas no repeats:false.
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.
Rotating Left, Then Right
Rotate the array left by one, then rotate it back to the right.
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]);
8 1 6 5 3
3 8 1 6 5
- 1Rotate left. Save
a[0], copy each element from the next position going forward, then put the saved value at the end. - 2Rotate right. Save the last element, copy each element from the previous position going backward, then put the saved value at index 0.
- 3Direction of the loop matters. Shifting right with a forward loop would copy the same value into every position.
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.
Reversing in Place
Reverse the array by swapping.
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]);
10 8 6 4 2
- 1Partner index. Element
iswaps witha.length - 1 - i: 0 with 4, 1 with 3. - 2Stop halfway.
a.length / 2is 2, so two swaps; going further would swap the pairs back. - 3The temporary variable keeps one value safe while the other is copied over it.
| Mistake | Effect |
|---|---|
| Max starts at 0 | Wrong when all values are negative |
| Pairs loop uses i < a.length | a[i + 1] goes out of bounds on the last pass |
| "At least one" returns false inside the loop | Decides after checking only the first element |
| Reverse loop runs to a.length | Every pair is swapped twice: no change |
| Shift right with a forward loop | One value copied into every position |
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.
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.