Skip to content
Official PYQ · 2008

GATE CS 2008 Q85 — Searching, Sorting, Hashing

Explain with AI

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 

Choose one option
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 Y=[2,5,8,12,16,23,38,56,72,91]Y = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] and we are searching for x=5x = 5.

  • Initially, i=0i = 0 and j=9j = 9.
  • k=(0+9)/2=4k = (0 + 9) / 2 = 4. Since Y[4]=16>5Y[4] = 16 > 5, the else branch executes: j=k=4j = k = 4.
  • Next iteration: k=(0+4)/2=2k = (0 + 4) / 2 = 2. Since Y[2]=8>5Y[2] = 8 > 5, we get j=k=2j = k = 2.
  • Next iteration: k=(0+2)/2=1k = (0 + 2) / 2 = 1. Since Y[1]=5==xY[1] = 5 == x, the loop terminates (due to the condition Y[k] != x), and the element is correctly found.

Now, consider searching for x=6x = 6 (which is not in the array):

  • Eventually, we reach a state where i=1i = 1 and j=2j = 2.
  • k=(1+2)/2=1k = (1 + 2) / 2 = 1.
  • Since Y[1]=5<6Y[1] = 5 < 6, the if branch executes: i=k=1i = k = 1.
  • In the next iteration, ii and jj remain 11 and 22 respectively. kk is calculated as 11 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 kk once we determine that Y[k]≠xY[k] \neq x:

  • If Y[k]<xY[k] < x, then xx must lie in the strictly right subarray, so we set i=k+1i = k + 1.
  • If Y[k]>xY[k] > x, then xx must lie in the strictly left subarray, so we set j=k−1j = k - 1.

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.

Published
Report a correction
Keep exploringMore Searching, Sorting, Hashing questions