/* Example 9.3: Sequential search Algorithm: Gilberg and Forouzan, p. 40 Modification: Peter Brusilovsky Reads array from the st input, then requests element to be found until it can be found. */ #include #define N 7 /* dimension of the array */ int readarray(int ar[], int n); int ordSeqSearch(int list[], int last, int target); main() { /* declare an array */ int testarray[N]; int mytarget, index; /* read data */ readarray(testarray, N); do { /* get target */ printf("Enter target: "); scanf("%d", &mytarget); /* find */ if ((index = ordSeqSearch(testarray, N, mytarget)) == -1 ) printf("Target %d not found\n", mytarget); else printf("Target %d is located at index %d\n", mytarget, index); } while(index == -1); /* loop ends when the requested element found */ return 0; } /* array input */ int readarray(int ar[], int n_of_elements) { int i; for (i = 0; i < n_of_elements; ++i) { printf("%d> ", i); scanf("%d", &ar[i]); } return 0; } /* finding index of the array element with the target value returns -1 if not found */ int ordSeqSearch(int list[], int last, int target) { int looker = 0; if (target > list[last-1]) return -1; while (target > list[looker]) looker++; /* the loop ended either because target < list[looker] or target == list[looker] */ if (target < list[looker]) /* i.e., if we got to the end of list with no success */ return -1; else /* found */ return looker; }