• edited by
11,895 views
30 30 votes

Consider the following C program that attempts to locate an element $x$ in an array $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. Change line 6 to: if $(Y[k] < x) i = k + 1$; else $j = k-1$; 
  2. Change line 6 to: if $(Y[k] < x) i = k - 1$; else $ j = k +1$; 
  3. Change line 6 to: if $(Y[k] < x) i = k$; else $j = k$;
  4. Change line 7 to: } while $((Y[k] == x) \&\& (i < j))$ ;

3 Answers

Best answer
37 37 votes

Answer should be A.

if( Y[k] < x) then i = k + 1;

if given element that  we are searching is greater, then searching will be continued in the upper half of array

otherwise $\mathbf{j = k - 1}$;

in the lower half.

Take few case in consideration i.e.

  1. All elements are same
  2. Increasing order with no repetition
  3. Increasing order with  repetition.
• edited by
6 6 votes
Just try to search Last element : it will go into infinite loop because of interger division.

i=k+1 will solve the problem.

lets elemets are : 10 20 30 40 50 60 70 80 90 100

now try to search 25 or 35 or 45 or 55 on above array so it will run into infinite loop.

so we need both the conditions=i=k+1 and j=k-1

P.S: This program is errorenous because of unsuccessful search.
5 5 votes

There are 2 changes to be made:

1. updation conditions : i=k+1 and j=k-1 //reason can be found in other ans

2.while loop condition : while (Y[k] != x) && (i < = j) //equal to added here , other ans missed this

let a[]={1,2,3,4,5,6,7,8,9,10};

Without 2nd condition f(a,10) will fail

 
Answer:
Position:
Show:

Related questions

61 61 votes
6 answers 6 answers
30.1k
30.1k views
Kathleen asked Sep 11, 2014
30,136 views
Consider the following C program that attempts to locate an element $x$ in an array $Y[ \ ]$ using binary search. The program is erroneous. f (int Y[10] , int x) { int i,...
74 74 votes
4 answers 4 answers
36.1k
36.1k views
Kathleen asked Sep 12, 2014
36,122 views
Which of the following are NOT true in a pipelined processor?Bypassing can handle all RAW hazardsRegister renaming can eliminate all register carried WAR hazardsControl h...
43 43 votes
6 answers 6 answers
22.1k
22.1k views
go_editor asked Apr 23, 2016
22,137 views
Consider the following C functions:int f1 (int n) { if(n == 0 || n == 1) return n; else return (2 * f1(n-1) + 3 * f1(n-2)); } int f2(int n) { int i; int X[N], Y[N], Z[N];...
37 37 votes
6 answers 6 answers
11.1k
11.1k views
go_editor asked Apr 23, 2016
11,077 views
Let $x_n$ denote the number of binary strings of length $n$ that contain no consecutive $0$s.The value of $x_5$ is $5$$7$$8$$16$