next up previous contents index Search
Next: 0.2.2 Binary Search Up: 0.2.1 Linear Search Previous: 0.2.1 Linear Search

0.2.1.1 Source Code

Below is an implementation of a linear search of an array of integers written C. Since this is the first program in the document I will preface it by saying that many of the examples will not compile and are simply illustrations of a concept. This one, and others, will compile, however. But to build most of the programs in this document you will need the global.h file from the introduction.






//+----------------------------------------------------------------------------
 //
 // File:     linsearch.c
 //
 // Module:   Linear Search Example
 //
 // Synopsis: Search, linearly.
 //
 // Author:	 sgasch
 //
 // Created    27 May 1999
 //
 //+----------------------------------------------------------------------------
 
 #include 
 #include 
 
 //
 // See introduction section of the document.
 //
 #include "global.h"
 
 #define NUM_ELEMENTS               100
 
 DWORD rgdwSearchSpace[NUM_ELEMENTS];
 DWORD dwLcv;
 BOOL fFound = FALSE;
 DWORD dwTarget;
 
 int main(VOID) 
 {
 	srand(1);
 
 	//
 	// initialize the array.
 	//
 	for (dwLcv = 0; dwLcv < NUM_ELEMENTS; dwLcv++) 
 	{
 		rgdwSearchSpace[dwLcv] = rand();
 		printf(" %d:   %d\n", dwLcv, rgdwSearchSpace[dwLcv]);
 	}
 
 	//
 	// ask which one they want to search for.
 	//
 	printf("Search for: ");
 	scanf("%d", &dwTarget);
 
 	//
 	// now find it -- by linear search.
 	//
 	dwLcv = 0;
 	while ((dwLcv < NUM_ELEMENTS) && !fFound) 
 	{
 		if (rgdwSearchSpace[dwLcv] == dwTarget) 
 		{
 			printf("Found at element %d!\n", dwLcv);
 			fFound = TRUE;
 		}
 		dwLcv++;
 	}
 
 	if (FALSE == fFound) 
 	{
 		printf("Sorry, not found.");
 	}
 
 	//
 	// Exit successfully.
 	//
 	return(0);
 }




Scott Gasch
1999-07-09