The recursive version of the binary search in the book:
int binarySearch(int[] array, int target) throws BSException { return int binarySearch(int[] array, int target) throws BSException {
return binarySearch(array, target, 0, array.length-1);
}
int binarySearch( int[] array, int target, int lower, int upper ) throws BSException {
int center, range;
range = upper - lower;
if( range < 0 ){
throw new BSException("Limits reversed");
} else if( range == 0 && array[lower] != target ){
throw new BSException("Element not in array");
}
if( array[lower] > array[upper] ){
throw new BSException("Array not sorted");
}
center = ((range)/2) + lower;
if( target == array[center] ){
return center;
} else if( target < array[center] ){
return binarySearch( array, target, lower, center - 1 );
}
else {
return binarySearch( array, target, center + 1, upper );
}
}
and the iterative version:
while( true ){
range = upper - lower;
if( range == 0 && array[lower] != target ){
throw new BSException("Element not in array");
}
About every other algorithm book, include TAOCP by Donald Knuth, Algorithm Design Manual, Programming Pearl, etc, has "valid case" of
while (low <= high) {
// ...
}
return -1; // not found
or a "not found" case of low > high
:
if (low > high) return -1; // not found
but the recursive and iterative algorithm in the book Programming Interviews Exposed used low > high
(meaning range < 0
) as BSException("Limits reversed")
and low == high
to check for "not found". Now, if range
is in fact less than 0, then the program would have thrown the exception of BSException("Limits reversed")
and never be able to report NotFound.
Consider the case of an array with just 2 elements, or the lower
and upper
only include 2 elements, say
lower is 0
upper is 1
center is (1-0)/2 + 0 = 0
Now, let's say target
is less than array[center]
, then upper = center - 1
and is -1
, while lower
stays as 0
. So we have upper < lower
meaning range < 0
but the recursive algorithm reports it as BSException("Limits reversed")
rather than NotFound, while the iterative doesn't see lower == upper
and go further with upper
as -1
and use array[upper]
and have strange behavior?