// TITLE: Binary search of an array // AUTHOR: Paul Curzon, modifed from Deitel & Deitel // DATE 23/7/2002 // DESCRIPTION: // This program randomly generates a series of test data of differing sizes // (5 - 100 positive integers) reading them into array a. // It then randomly generates a search key // and searches the elements of the array using binary search. // It returns a table giving the amount of data the test was // run on and the number of comparisons made. #include #include #include enum SearchResult {FOUND, NOT_FOUND}; SearchResult binarySearch(int array[], int key, int high, int *count); void fill_array(int array[], int sizeOfData); const int RANGE = 200; // random data used in range 0-199 int main() { const int arraySize = 100; int a[arraySize]; FILE *resultsFile; resultsFile = fopen("bsrch.dat", "w"); // open the file lsrrch.dat for writing ("w") if (resultsFile != NULL) // file successfully opened { // seed the random number generator so it gives different // random numbers each time srand ( time (0) ); // Table headings printf ("Found\t Data Size\t Comparisons Needed\n" ); //\t puts in a tab character, \n a new line fprintf (resultsFile, "Data Size\t Found/Not found\tComparisons Needed\n" ); fill_array(a, arraySize); // Generate table for data of different sizes // giving number of comparisons each time int count = 0; // number of comparisons this time SearchResult result; // result of this search int searchKey = rand() %RANGE; result = binarySearch(a, searchKey,arraySize, &count); for(int i = 0; i high) { return NOT_FOUND; } } }