As we also discussed in class, binary search is an inherently recursive algorithm. The pseudocode that we wrote for a binary search method that looks for item target between indices lo and hi in array a looked something like this:
boolean binarySearch(Object target, Object[] a, int lo, int hi)
if lo and hi have not crossed
compute index mid
if target = a[mid]
return true
else if target < a[mid]
do binary search between lo and mid-1 and return this value
else //target > a[mid]
do binary search between mid+1 and hi and return this value
else
return false;
recBinarySearch(a, target, 0, a.length-1)the call in your driver will now look like this:
recBinarySearch(a,target)Note that all the work is still being done in your original (4-parameter) recBinarySearch method; the new (2-parameter) method just calls it. It is often useful to "set up" a call to a recursive method in this way so that the extra parameters needed by the recursive method are not visible from the outside.