121: Computer Science 1 --- Lecture February 20-21

Topics:

More on arrays
Searching Lists Sequentially
Linear Search
Iterative and
Recursive Search
Passing Arrays as Functions

Linear or Sequential search works by scanning the elements of an array until the key value is found. We illustrate this by writing a function that uses a simple for loop to do the scan from left to right; and we return from the function when the key element is first found. We also provide a recursive version of linear search that works by comparing the key with the last element of the array. If same we return the index of the last element. If different we recursive search the smaller list which ignores the last item. The base case is for the list of size 0, the empty list, in which case we return –1 indicating search failure. The recursive search effectively scans the list from right to left.

The following program creates a array of data (100 random integers in range 0-99). The program then prompts the user to enter in a search key. A linear search function is called to locate the key. This is repeated using a recursive search method.

 
 
// Program to illustrate both 
//  Linear search and a 
//   Recursive search of an array
#include < iostream >
 
using std::cout;
using std::cin;
using std::endl;
 
#include < cstdlib >
void Display( const int [], int );
int linearSearch( const int [], int, int );
int RecursiveSearch( const int [], int, int );
 
int main()
{
   const int arraySize = 100;
   int a[ arraySize ], searchKey, position;
 
   for ( int x = 0; x < arraySize; x++ )  // create some data
      a[ x ] = rand() % 100;
 
   Display (a, arraySize);
 
  // Do a sequential search of list 
   cout << "Enter integer search key:" << endl;
   cin >> searchKey;
   position = linearSearch( a, arraySize, searchKey );
 
   if ( position != -1 )
      cout << "Linear search found value in position " << position << endl;
   else
      cout << "Linear search did not find value " << endl;
 
   // Do a recursive search of the list
 
   cout << "Enter another integer search key:" << endl;
   cin >> searchKey;
   position = RecursiveSearch( a,  arraySize, searchKey);
 
   if ( position != -1 )
      cout << "Recursive search found value in position " << position << endl;
   else
      cout << "Recursive search did not find value " << endl;
 
 
   return 0;
}
 
 
void Display ( const int List[], int size)
{   for (int i = 0 ; i < size; ++i)
          cout << List[i] << "\t";
     cout << "\n";
}
 
int linearSearch( const int List[], int size, int key)
{
   for ( int i = 0; i < size; i++ )
      if ( List[ i ] == key )
         return i;
 
   return -1;
}
 
int RecursiveSearch( const int List[], int size, int key )
{
        if (size <= 0)
               return -1;
        else if (List[size-1] == key)
                       return size-1;
             else 
                       return RecursiveSearch(List, size-1, key);
}