/* File: binary_search.c Testing Binary Search */ #include #include #include #include #include "sorting.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. */ index b_search(data key, data A[], index low, index 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 b_search(key, A, mid+1, high) ; } else { return b_search(key, A, low, mid - 1) ; } } main(int argc, char *argv[]) { data *A, key ; index n, i, r ; long seed ; int count, reps ; if (argc != 4) { fprintf(stderr, "Usage: binary_search filename reps rseed \n") ; exit(-1) ; } /* Get number of repetitions */ r = sscanf(argv[2], "%d", &reps) ; if (r != 1) { printf("Number of repetitions must be an integer!\n") ; exit(-1) ; } /* Set random seed */ r = sscanf(argv[3], "%ld", &seed) ; if (r != 1) { printf("Random seed must be an integer!\n") ; exit(-1) ; } srand48(seed) ; n = readarray(argv[1], &A) ; printf("n = %d\n", n) ; count = 0 ; for (i = 0 ; i< reps ; i++) { key = (data) lrand48() ; r = b_search(key, A, 0, n-1) ; if (r >= 0) { printf("Found: key = %12d, A[%07d] = %12d\n", key, r, A[r]) ; count++ ; } } printf("Number of hits: %d\n", count) ; }