/* File: linear_search.c Testing Linear Search */ #include #include "sorting.h" /* Search for item with value equal to key in array A. Return the index of the item, or -1 if none found. */ index l_search(data key, data A[], index low, index high) { int i ; for (i = low ; i <= high ; i++) { if (key == A[i]) return i ; } return -1 ; } main(int argc, char *argv[]) { data *A, key ; index n, i, r ; long seed ; int count, reps ; if (argc != 4) { fprintf(stderr, "Usage: linear_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 = l_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) ; }