Two Loops, Still Linear
Here is a method that searches for a target in two arrays, one after the other:
public boolean contains(int[] a, int[] b, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return true;
}
}
for (int i = 0; i < b.length; i++) {
if (b[i] == target) {
return true;
}
}
return false;
}
Suppose both arrays have length . How much work does this do, and what is its Big-Oh?
We have two loops, one after the other. Each is a linear search: a constant amount of work per element, repeated over elements. In the worst case the target is in neither array, so we scan both all the way through. That is about steps for the first loop and for the second, roughly in total.
And is . The factor of is a coefficient, and we suppress coefficients. When loops run one after another, their work adds. Running a linear scan twice, or three times, or any constant number of times, is still linear.
I set both arrays to length to keep the arithmetic simple. If they have sizes and , the work is . The work is still linear. It is just that what adds is and rather than and .