Recursive Algorithm: Searching a List

Discussion

A list described by the following structure:
struct  ListType

{
   int  length ;   // number of elements in the list


   int  info[ MAX_ITEMS ] ;

           
} ;	

ListType   list ;



Suppose we have:
And we want to search if "value" exists in list using a function call:
bool  ValueInList( ListType  list , int  value , int  startIndex );




base case

if (list[startIndex] == value) return true;

general case

if(startIndex < length of list)

       return ValueInList( list, value, startIndex + 1 ) ;

Solution

bool ValueInList ( ListType  list , int  value, int startIndex )

// Searches list for value between positions startIndex
// and  list.length-1
// Pre: list.info[ startIndex ] . . list.info[ list.length - 1 ]
// 	 contain values to be searched
//  Post:  Function value = 
//	  ( value exists in list.info[ startIndex ] . . 
//   list.info[ list.length - 1 ] )
{  
   if  ( list.info[startIndex] == value )    // one base case 	return  true ;
   else  if  (startIndex == list.length -1 ) // another base case
		return  false ;
	else			 			     // general case	
     	return ValueInList( list, value, startIndex + 1 ) ;
}

 


 

 

 

© Lynne Grewe