Consider the following C program that attempts to locate an element in an array using binary search. The program is erroneous.
f (int Y[10] , int x) {
int i, j, k;
i= 0; j = 9;
do {
k = (i+ j) / 2;
if( Y[k] < x) i = k;else j = k;
} while (Y[k] != x) && (i < j)) ;
if(Y[k] == x) printf(" x is in the array ") ;
else printf(" x is not in the array ") ;
}
On which of the following contents of and does the program fail?
View worked solution
Answer: C
The given binary search implementation has a bug: when updating the search boundaries, it uses i = k instead of i = k + 1, and j = k instead of j = k - 1. This can lead to an infinite loop when the search range cannot be reduced further.
Let us trace Option C where and (let ):
- Initial state: ,
- Iteration 1: . Since , we set . Condition is true.
- Iteration 2: . Since , we set . Condition is true.
- Iteration 3: . Since , we set . Condition is true.
- Iteration 4: . Since , we set . Condition is true.
- Iteration 5: . Since , we set . Condition is true.
At this point, and remain unchanged, and remains in all subsequent iterations. The program enters an infinite loop and fails to terminate.
Free practice · Your answers on this page are not saved.
