187k views
4 votes
Write a function with the following header: int search(int A[], int lo, int hi, int item) The function uses a loop to examine all the numbers stored in the slice A[lo] ... A[hi], in order, starting with A[lo], A[lo+1]... etc. (you can modify the sequential search algorithm - see program 8-1 in text). If the item is found in the array A, the function returns the index of the cell that contains item; if item is not found, the function returns -1. A global variable is incremented prior to each comparison in the search function; this variable must be initialized to zero before the function call and its value is printed after the function call. Compile and test in a script session. Test should show a case when the item is found and a case when it is not found. The number of comparisons should be printed

User Dmuir
by
7.0k points

1 Answer

2 votes

Final answer:

The function search() is a modified sequential search algorithm that examines all the numbers in the array A[] from A[lo] to A[hi]. It returns the index of the cell that contains the item if found, and -1 if the item is not found. A global variable is incremented before each comparison, and its value is printed after the function call.

Step-by-step explanation:

The function search() is a modified sequential search algorithm that examines all the numbers in the array A[] from A[lo] to A[hi], in order, to find the item. It returns the index of the cell that contains the item if found, and -1 if the item is not found. A global variable is incremented before each comparison, and its value is printed after the function call.

Here is an example implementation of the search() function:

int search(int A[], int lo, int hi, int item) {
int comparisons = 0;
for (int i = lo; i <= hi; i++) {
comparisons++;
if (A[i] == item) {
return i;
}
}
cout << 'Number of comparisons: ' << comparisons << endl;
return -1;
}

In this implementation, the variable 'comparisons' is incremented before each comparison, and its value is printed after the loop is finished.

User TRiG
by
6.9k points