Skip to main content

GATE CSE 2008Algorithms › Program & Function TracingVerified

GATE CSE 2008 PYQ: Consider the following C program that attempts to locate an element x x x in an array Y [ ] Y[ \ ] Y [ ]…

Consider the following C program that attempts to locate an element xx in an array Y[ ]Y[ \ ] using binary search. The program is erroneous. 

  1. f (int Y[10] , int x) {
  2. int i, j, k;
  3. i= 0; j = 9;
  4. do {
  5. k = (i+ j) / 2;
  6. if( Y[k] < x) i = k;else j = k;
  7. } while (Y[k] != x) && (i < j)) ;
  8. if(Y[k] == x) printf(" x is in the array ") ;
  9. else printf(" x is not in the array ") ;
  10. }

On which of the following contents of YY and xx does the program fail? 

  1. A
    YY is [1 2 3 4 5 6 7 8 9 10][1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9 \ 10] and x<10x < 10
  2. B
    YY is [1 3 5 7 9 11 13 15 17 19][1 \ 3 \ 5 \ 7 \ 9 \ 11 \ 13 \ 15 \ 17 \ 19] and x<1x < 1
  3. C
    YY is [2 2 2 2 2 2 2 2 2 2][2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2] and x>2x > 2
    Correct answer
  4. D
    YY is [2 4 6 8 10 12 14 16 18 20][2 \ 4 \ 6 \ 8 \ 10 \ 12 \ 14 \ 16 \ 18 \ 20] and 2<x<20 2 < x < 20 and xx is even

Answer

(C) Y Y Y is [ 2 2 2 2 2 2 2 2 2 2 ] [2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2 \ 2] [ 2 2 2 2 2 2 2 2 2 2 ] and x > 2 x > 2 x > 2

Approach

The bug is in the assignment of the new search bounds: the code uses i = k and j = k instead of i = k+1 and j = k-1. This can cause an infinite loop when the search interval shrinks to two adjacent indices i and j = i+1 and the element at index i is still less than x. At that point k = i, the condition Y[k] &lt; x becomes true, i is set to k (unchanged), and the loop never progresses. Simulate each option to see which one triggers this condition.

The erroneous binary search fails when the updated bounds do not shrink the interval properly. The only option that triggers an infinite loop is C: all array elements are 2 and x &gt; 2, so the search always moves i to k and eventually gets stuck with i=8 and j=9, recomputing k=8 forever. Thus the program fails on option C.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.