Consider the following program that attempts to locate an element x in a…
PYQ GATE 1996Modified — slightly modified from the official paper; see the solution
Consider the following program that attempts to locate an element x in a sorted array a[1..N] using binary search. Assume N > 1. The program is erroneous. Under what condition does the program fail?
i = 1;
j = N;
do {
k = floor((i + j) / 2);
if (a[k] < x)
i = k + 1;
else
j = k;
} while (a[k] != x && i < j);
if (a[k] == x)
print("x is in the array");
else
print("x is not in the array");
- A.
x is the last element of the array a[]
- B.
x is greater than all elements of the array a[]
- C.
Both of the above
- D.
x is less than the last element of the array a[]
Attempted by 272 students.
Sign up free to check your answer
Sign up freeLoading lesson…

