Question
Consider the C function given below. Assume that the array listA contains n (> 0) elements, sorted in ascending order.
int ProcessArray(int *listA, int x, int n) {
int i, j, k;
i = 0;
j = n - 1;
do {
k = (i + j) / 2;
if (x <= listA[k])
j = k - 1;
if (listA[k] <= x)
i = k + 1;
} while (i <= j);
if (listA[k] == x)
return(k);
else
return -1;
}
Which one of the following statements about the function ProcessArray is CORRECT?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2014 answer key
Solution
Analyze the loop invariant and termination conditions of the ProcessArray function.
-
Inspect
ProcessArray(int *listA, int x, int n):- The array
listAis sorted in ascending order with elements. - Pointers and .
- Inside the
do-whileloop:- chooses the midpoint.
- If , search interval shrinks on the right: .
- If , search interval shrinks on the left: .
- The array
-
When :
- Both conditions and are satisfied.
- Consequently, both updates execute: and .
- This immediately causes , so the
do-while (i <= j)loop terminates. - After the loop, the check
if (listA[k] == x)is evaluated. Since still holds the index where , it successfully returns .
-
When :
- Only updates, halving the search space to the left.
-
When :
- Only updates, halving the search space to the right.
-
When is not present:
- The loop terminates with , and
listA[k] != x, returning .
- The loop terminates with , and
Thus, this function is a correct implementation of binary search (option B).
B
Assuming that setting both i and j when x == listA[k] causes an error, whereas it cleanly terminates the search and returns k.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 3
- Question
- 52 of 65, printed as CS Q.42
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.