Algorithms | Searching | Question 6

In the above question, the correction needed in the program to make it work properly is (GATE CS 2008)
(A) Change line 6 to: if (Y[k] < x) i = k + 1; else j = k-1;
(B) Change line 6 to: if (Y[k] < x) i = k – 1; else j = k+1;
(C) Change line 6 to: if (Y[k] <= x) i = k; else j = k;
(D) Change line 7 to: } while ((Y[k] == x) && (i < j));


Answer: (A)

Explanation: Below is the corrected function

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 + 1; else j = k - 1;
       } while(Y[k] != x && i < j);
   if(Y[k] == x) printf ("x is in the array ") ;
   else printf (" x is not in the array ") ;
}

Reference: http://en.wikipedia.org/wiki/Binary_search_algorithm#Implementations

Quiz of this Question



My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :



Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.