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 ") ;
}
The correction needed in the program to make it work properly is
View worked solution
Answer: A
To identify the error in the given binary search implementation, let us analyze the behavior of the loop updates when the search interval becomes small.
Consider an array and we are searching for .
- Initially, and .
- . Since , the
elsebranch executes: . - Next iteration: . Since , we get .
- Next iteration: . Since , the loop terminates (due to the condition
Y[k] != x), and the element is correctly found.
Now, consider searching for (which is not in the array):
- Eventually, we reach a state where and .
- .
- Since , the
ifbranch executes: . - In the next iteration, and remain and respectively. is calculated as again. This results in an infinite loop because the search space never shrinks.
Correction:
To guarantee that the search space strictly shrinks in every step and to avoid infinite loops, we must exclude the index once we determine that :
- If , then must lie in the strictly right subarray, so we set .
- If , then must lie in the strictly left subarray, so we set .
Thus, changing line 6 to if (Y[k] < x) i = k + 1; else j = k - 1; makes the program work correctly.
Free practice · Your answers on this page are not saved.
