// File: bsearch.C // Testing Binary Search #include #include #include #include #include #include #include "array.h" // Recursively search for item with value equal to key // in sorted array A. Return the index of the item, // or -1 if none found. int bsearch(DATA key, Array A, int low, int high) { int mid ; // No such item? if (low > high) return -1 ; mid = (low + high) / 2 ; // check middle if (A[mid] == key) { return mid ; } else if (A[mid] < key) { return bsearch(key, A, mid+1, high) ; } else { return bsearch(key, A, low, mid - 1) ; } } main(int argc, char *argv[]) { DATA key ; int n, i, r ; long seed ; int count, reps ; ifstream ifile ; struct stat sbuf ; if (argc != 4) { cerr << "Usage: bsearch reps seed fname" << endl ; exit(1) ; } reps = atoi(argv[1]) ; seed = atoi(argv[2]) ; if (reps <= 0 || seed <= 0) { cerr << "Bad size or seed" << endl ; exit(1) ; } // get file size // r = stat(argv[3], &sbuf) ; if (r != 0) { cerr << "Cannot get file size" << endl ; exit(1) ; } // n = Number of data items in the file // n = sbuf.st_size / sizeof(DATA) ; cout << "reps = " << reps << " seed = " << seed << endl ; cout << "number of items = " << n << endl ; ifile.open(argv[3]) ; if (ifile == NULL) { cerr << "Could not open file " << argv[3] << endl ; exit(1) ; } Array A(n, seed) ; ifile.read((char *) A.arr, n * sizeof(DATA) ) ; count = 0 ; for (i = 0 ; i< reps ; i++) { key = (DATA) drand48() ; r = bsearch(key, A, 0, A.length()-1) ; if (r >= 0) { cout << "Found: key = " << key << " A[" << r << "] = " << A[r] << endl ; count++ ; } } cout << "Number of hits: " << count << endl ; }