dev only
Implementing Array Algorithms
A handful of patterns, all built from a loop plus a little bookkeeping, cover almost everything you'll want to do with an array.
Sum / Average (Accumulator)
double sum = 0;
for (double reading : sensorReadings)
{
sum += reading;
}
double average = sum / sensorReadings.length;
Min / Max
double max = sensorReadings[0]; // seed with the first element, not 0 — a reading could be negative
for (double reading : sensorReadings)
{
if (reading > max)
{
max = reading;
}
}
Search — Check Everything Before Giving Up
public static boolean contains(double[] values, double target)
{
for (double v : values)
{
if (v == target)
{
return true; // fine to return early on a MATCH
}
}
return false; // only after checking every element
}
Looping Back to Front
Same shape, just counting down:
for (int i = values.length - 1; i >= 0; i--)
{
// process values[i], starting from the end
}
"At Least One" / "All" / "Count"
// at least one has the property
for (double v : values) { if (isFaulty(v)) return true; }
return false;
// all have the property (check the NEGATION, bail early on a counter-example)
for (double v : values) { if (!isFaulty(v)) return false; }
return true;
// count how many have the property
int count = 0;
for (double v : values) { if (isFaulty(v)) count++; }
Duplicates
Adjacent only — a single loop comparing neighbors:
for (int i = 0; i < values.length - 1; i++)
{
if (values[i] == values[i + 1]) return true;
}
Anywhere in the array — a nested loop comparing every pair:
for (int i = 0; i < values.length; i++)
{
for (int j = i + 1; j < values.length; j++)
{
if (values[i] == values[j]) return true;
}
}
Reversing (Swap From Both Ends)
int start = 0, end = values.length - 1;
while (start < end)
{
double temp = values[start];
values[start] = values[end];
values[end] = temp;
start++;
end--;
}
Common Pitfalls
- Seeding min/max with
0instead of the first element. If every real value is negative (or all above some baseline),0is a wrong starting point that never gets replaced correctly. - Returning "not found" from inside the loop. Only a match should return early; "not found" has to wait until the loop has checked every element.
- Comparing
values[i]tovalues[i+1]all the way to the last index. This reads one past the end — the adjacent-duplicate loop must stop atlength - 2(i.e., bound the loop byi < values.length - 1).
Key Takeaways
- Sum/average, min/max, search, and property-counting are all the same basic shape: a loop plus a little state (an accumulator, a running best, a counter, or an early return).
- A search for "not found" must check every element before concluding absence; a search for a match can return the instant it's found.
- Adjacent-duplicate checks are a single loop; any-pair duplicate checks need a nested loop.
- Reversing in place swaps from both ends toward the middle using a temporary variable.
Derived from csawesome-2026: unit-4-data-collections/4.05-implementing-array-algorithms.md (CSA 4.5)