A Public Method and a Private Helper
Look at the two recursive search methods we have been working on.
public static boolean binarySearch(int[] arr, int target, int low, int high) { ... }
public static boolean linearSearch(int[] arr, int target, int start) { ... }
Each of them expects the client to pass one or more index parameters that are really internal details of the method, something the method needs in order to call itself. The client has to know what those indices mean, and the client can pass an invalid value. For example, what happens if a client calls linearSearch with a start index that is negative or greater than or equal to the length of the array?
- If
startis negative, we get anArrayIndexOutOfBoundsExceptionwhen we try to accessarr[start]. We may be content with that, but the error message talks about an array access, which is an internal detail of our method rather than anything the client did. We can do better by checking for this case ourselves and throwing anIllegalArgumentException, which says plainly that the client passed a bad argument. - If
startis greater than or equal toarr.length, we immediately returnfalse. We could read that as a legitimate answer, since there is nothing to search. But it is more likely a mistake on the client’s part, and answeringfalsehides the mistake instead of reporting it.
So let’s take the choice away from the client. We can overload the linearSearch method and write a public method that takes only the array and the target, and have it call a private helper that takes the start index. The client cannot call the helper, so the index is never supplied from outside and never wrong. The overloaded methods look like this:
public static boolean linearSearch(int[] arr, int target) {
return linearSearch(arr, target, 0);
}
private static boolean linearSearch(int[] arr, int target, int start) {
if (start >= arr.length) {
return false; // base case: reached the end of the array
} else if (arr[start] == target) {
return true; // base case: found the target
} else {
// recursive case: search the rest of the array
return linearSearch(arr, target, start + 1);
}
}
We will do the same thing for binarySearch in the next section.