// File: lsearch.C // Testing Linear 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 lsearch(DATA key, Array A, int low, int high) { int i ; for (i = low ; i <= high ; i++) { if (key == A[i]) return i ; } return -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: lsearch 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 << "File size = " << 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 = lsearch(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 ; }