Lori first coded recursive binarySearch() as follows. Where did she go wrong?

```
public static int binarySearch( int[]coll, int target ) {
int first = 0,
last = target.length,
mid = ( first + last ) / 2;
if ( first > last ) return -1; // failure — base case
if ( coll[ mid ] == target ) // success — base case
return mid;
if ( coll[ mid ] < target ) { // recursive cases
last = mid – 1;
return binarySearch( coll, target );
}
else {
first = mid + 1;
return binarySearch( coll, target );
}
}


The mistake is in the recursive part and has to do with first and last, which are reset to '0' and 'target.length' in the beginning of each call. Consequently, the search does not progress toward the base case and will continually check the same midpoint over and over. Each invocation should narrow the search. This can be done by passing in the bounds of the search space as parameters, as is suggested in the chapter.

Computer Science & Information Technology

You might also like to view...

The delete operator should only be used on pointers that

A) have not yet been used. B) have been correctly initialized. C) point to storage allocated by the new operator. D) are appropriately dereferenced. E) None of the above

Computer Science & Information Technology

A ____ language is a language used to describe the content and structure of documents.

A. markup B. parsed C. validated D. dictionary

Computer Science & Information Technology

Consider a pair of processes X and Y that use the communication service B to communicate with one another. Suppose that X is a client and Y a server and that an invocation consists of a request message from X to Y (that carries out the request) followed by a reply message from Y to X. Describe the classes of failure that may be exhibited by an invocation.

What will be an ideal response?

Computer Science & Information Technology

The default folder where custom template files are stored is named ________

A) Your Templates Folder B) Word Custom Templates C) Office Templates folder D) Custom Office Templates

Computer Science & Information Technology