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. 

 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 

  1. A
    Change line 6 to: if (Y[k]<x)i=k+1(Y[k] < x) i = k + 1; else j=k−1j = k-1;
    Correct answer
  2. B
    Change line 6 to: if (Y[k]<x)i=k−1(Y[k] < x) i = k - 1; else j=k+1 j = k +1;
  3. C
    Change line 6 to: if (Y[k]<x)i=k(Y[k] < x) i = k; else j=kj = k;
  4. D
    Change line 7 to: } while ((Y[k]==x)&&(i<j))((Y[k] == x) \&\& (i < j)) ;

Answer

(A) Change line 6 to: if ( Y [ k ] < x ) i = k + 1 (Y[k] < x) i = k + 1 ( Y [ k ] < x ) i = k + 1 ; else j = k − 1 j = k-1 j = k − 1 ;

Approach

The given binary search is erroneous because it never excludes the just-tested midpoint k from the next search interval (it sets i = k or j = k). This can cause an infinite loop when the interval collapses to two adjacent elements straddling k. The standard fix is to exclude k going forward: set i = k + 1 when Y[k] &lt; x, else j = k - 1. This is exactly option A.

The only correction that makes the binary search progress correctly is replacing line 6 with i = k + 1 when Y[k] &lt; x and j = k - 1 otherwise, as in option A.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.