Lesson 11: Array and ArrayList Algorithms — Accumulation, Filtering and Searching
Once you can traverse an array or an ArrayList, you can build the small algorithms that free-response questions ask for again and again. Most of them follow one of three patterns. Accumulation builds a result by combining every element: a sum, a product, a count, or a concatenated String. Filtering selects the elements that satisfy a condition and either counts them, collects them into a new list, or processes them in place. Searching looks for a particular value or for the first element satisfying a condition, and stops when it finds it. Recognizing which pattern a question wants is half the battle.
Accumulation starts with an identity value — 0 for a sum, 1 for a product, an empty String for concatenation — and updates it for each element. The classic bug is initializing the accumulator to the wrong value, such as starting a product at 0, which guarantees a result of 0, or starting a maximum search at 0, which fails for all-negative data. Filtering adds a condition inside the traversal: if the element qualifies, act on it, and if it does not, skip it. The two patterns combine freely: you can sum only the elements above a threshold, or count only the Strings longer than five characters.
Searching comes in two forms. A linear search checks elements one by one from the start until it finds the target or reaches the end, and it works on any data, sorted or not. The search should return the position where the value was found, or a signal such as −1 when it is absent, and it should stop as soon as the value is found rather than continuing to the end. A common refinement is to search for the first element satisfying a condition rather than an exact value, such as the first score above 90, which is the same algorithm with a different test. The worst case for a linear search is checking every element, which happens when the target is last or absent.
Writing these algorithms as methods is good practice for the exam, because free-response questions usually ask for a method that operates on an array or ArrayList passed as a parameter. The method should not assume anything about the data beyond what the question states: check for an empty array where the question allows one, use the length or size for bounds, and return a value of the declared type on every path. A search method, for example, must return −1 after the loop if the value was never found, and that return statement must sit outside the loop, not inside it.
A search that finds what it is looking for should stop immediately, and the cleanest way to do that is to return as soon as the target is found. Returning from inside the loop ends the method at once, so the code after the loop runs only when the target was never found — the natural place for the −1 return. This early-return pattern also keeps the code short: there is no need for a found flag or a break statement, because the return does both jobs. The same idea applies to methods that test a condition over a collection: return false as soon as a counterexample appears, and return true only after the whole traversal completes, since a single counterexample is enough to settle the answer.
A worked example
Worked example: the method below counts how many Strings in a list have length greater than a given limit, combining filtering with accumulation. The counter starts at 0, each qualifying String increments it, and the method returns the final count.
public int countLongStrings(ArrayList<String> words, int minLength)
{
int count = 0;
for (int i = 0; i < words.size(); i++)
{
if (words.get(i).length() > minLength)
{
count++;
}
}
return count;
}
// countLongStrings(["apple", "pear", "banana"], 4) returns 2
The traversal uses words.size() as its bound, the condition words.get(i).length() > minLength filters the elements, and the accumulator count starts at 0 and grows by one per qualifying word. 'Apple' has length 5 and qualifies, 'pear' has length 4 and does not, and 'banana' has length 6 and qualifies, so the result is 2. Notice that the return sits after the loop: returning inside the loop would end the method after the first element. In your own methods, check that every return is placed where it belongs.
Key Terms
- Accumulation
- Building a result by combining every element, such as a sum or a count.
- Filtering
- Selecting elements that satisfy a condition and acting only on those.
- Linear search
- Checking elements one by one until the target is found or the data run out.
- Identity value
- The starting value of an accumulator: 0 for a sum, 1 for a product.
- Traversal
- Visiting each element of an array or list in turn.
Discussion Questions
- Why must a product accumulator start at 1 and not 0?
- How is searching for the first element above 90 like searching for an exact value?
- Where must the 'not found' return go in a search method, and why?
Practice Questions
- Write the loop header to traverse an int array named data.
- A linear search checks 100 elements and the target is absent. How many comparisons are made?
- What should a search method return when the value is not found?
- An accumulator for a sum is initialized to 1 by mistake. What goes wrong?
- Why should a method use data.length rather than a fixed number as its loop bound?
Show answers
- for (int i = 0; i < data.length; i++)
- 100, because every element must be checked before concluding the target is absent.
- A signal such as −1, as specified by the question.
- Every result is one too large, because the sum starts with an extra 1.
- So it works for an array of any size, including one whose size changes.