Discussion
BinarySearch takes sorted array info, and two subscripts,
fromLoc and toLoc, and item as arguments. It returns false
if item is not found in the elements info[fromLoc…toLoc].
Otherwise, it returns true.
BinarySearch can be written using iteration, or using recursion
|
Solution
template<class ItemType>
bool BinarySearch ( ItemType info[ ] , ItemType item ,
int fromLoc , int toLoc )
// Pre: info [ fromLoc . . toLoc ] sorted in ascending order
// Post: Function value = ( item in info [ fromLoc .. toLoc] )
{ int mid ;
if ( fromLoc > toLoc ) // base case -- not found
return false ;
else {
mid = ( fromLoc + toLoc ) / 2 ;
if ( info [ mid ] == item ) //base case-- found at mi
return true ;
else if ( item < info [ mid ] ) // search lower half
return BinarySearch ( info, item, fromLoc, mid-1 ) ;
else // search upper half
return BinarySearch( info, item, mid + 1, toLoc ) ;
}
}
|