Recursive Algorithm: Binary Search of Sorted Array

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




base case

If remaining list has 0 elements (fromLoc > toLoc), there is no more processing to do.

general case

if ( item is stored at mid=(fromLoc+toLoc)/2 ) 
     return true;
else if (item < info[mid]) //recall sorted array
     return Binary Search from 0 to mid;
else
     return Binary Search from mid to toLoc;

       

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 ) ;
         }           
} 	


 


 

 

 

© Lynne Grewe