Skip to content
Official PYQ · 2008

GATE CS 2008 Q84 — 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 ") ;
 }

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

Choose one option
View worked solution

Answer: C

The given binary search implementation has a bug: when updating the search boundaries, it uses i = k instead of i = k + 1, and j = k instead of j = k - 1. This can lead to an infinite loop when the search range cannot be reduced further.

Let us trace Option C where Y=[2,2,2,2,2,2,2,2,2,2]Y = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] and x>2x > 2 (let x=3x = 3):

  • Initial state: i=0i = 0, j=9j = 9
  • Iteration 1: k=⌊(0+9)/2⌋=4k = \lfloor(0+9)/2\rfloor = 4. Since Y[4]=2<3Y[4] = 2 < 3, we set i=k=4i = k = 4. Condition (Y[4]≠3)∧(4<9)(Y[4] \neq 3) \land (4 < 9) is true.
  • Iteration 2: k=⌊(4+9)/2⌋=6k = \lfloor(4+9)/2\rfloor = 6. Since Y[6]=2<3Y[6] = 2 < 3, we set i=k=6i = k = 6. Condition (Y[6]≠3)∧(6<9)(Y[6] \neq 3) \land (6 < 9) is true.
  • Iteration 3: k=⌊(6+9)/2⌋=7k = \lfloor(6+9)/2\rfloor = 7. Since Y[7]=2<3Y[7] = 2 < 3, we set i=k=7i = k = 7. Condition (Y[7]≠3)∧(7<9)(Y[7] \neq 3) \land (7 < 9) is true.
  • Iteration 4: k=⌊(7+9)/2⌋=8k = \lfloor(7+9)/2\rfloor = 8. Since Y[8]=2<3Y[8] = 2 < 3, we set i=k=8i = k = 8. Condition (Y[8]≠3)∧(8<9)(Y[8] \neq 3) \land (8 < 9) is true.
  • Iteration 5: k=⌊(8+9)/2⌋=8k = \lfloor(8+9)/2\rfloor = 8. Since Y[8]=2<3Y[8] = 2 < 3, we set i=k=8i = k = 8. Condition (Y[8]≠3)∧(8<9)(Y[8] \neq 3) \land (8 < 9) is true.

At this point, i=8i = 8 and j=9j = 9 remain unchanged, and kk remains 88 in all subsequent iterations. The program enters an infinite loop and fails to terminate.

Free practice · Your answers on this page are not saved.

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