Monday, November 18, 2024
Google search engine
HomeData Modelling & AIAlgorithms | Searching | Question 6

Algorithms | Searching | Question 6

C++




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. }


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

Hence Option(A) is the correct option.

Quiz of this Question
Please comment below if you find anything wrong in the above post

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments