retagged by
6,651 views
27 27 votes

Consider the following program that attempts to locate an element $x$ in an array $a[ ]$ using binary search. Assume $N > 1$. The program is erroneous. Under what conditions does the program fail?

var i,j,k: integer; x: integer;
    a: array; [1..N] of integer;
begin	i:= 1; j:= n;
repeat	
    k:(i+j) div 2;
    if a[k] < x then i:= k
    else j:= k
until (a[k] = x) or (i >= j);
    
if (a[k] = x) then
    writeln ('x is in the array')
else
    writeln ('x is not in the array')
end;

2 Answers

Best answer
42 42 votes

The code is wrong here

k=(i+j) / 2;
if (a[k] < x) then i = k;
else j = k;

The (correct) code should be:

k=(i+j) / 2;
if (a[k] < x) then i = k + 1;
else j = k - 1;


We can try an example with the given code in question

Let the array be $\qquad a[1,2,3,4,5,6,7,8,9,10]$
Index numbers$\qquad \quad1,2,3,4,5,6,7,8,9,10$
Let $x=10$; now run the code;

Initially $i = 1, j=10$;

first time  $k =(i+j) /2 = 11/2 =5.5 = 5$ (because of integer type) $=i$

second time $= k =(i+j) /2 =15/2 =7.5 =7 =i$

third time $=  k =(i+j) /2 = 17/2 = 8.5 = 8 =i$

fourth time $=  k =(i+j) /2 = 18/2 = 9 = i$

fifth time  $=  k =(i+j) /2 = 19/2 = 9.5 =9 = i$

sixth time $=  k =(i+j) /2 = 19/2 = 9.5 =9 = i$

seventh time $=  k =(i+j) /2 = 19/2 = 9.5 =9 = i$


Going to infinite loop (run time error)

For terminating the loop, it should be $i = k + 1$  instead of $i =k$ and $j = k - 1$ instead of $j = k$;

edited by
11 11 votes

when input is [2 2 2 2 2 2 2 2 2 2] and search key x > 2 

i=1   j=10     k= ((1+10)/ 2)) = 5

i=5   j=10     k= ((5+10)/ 2)) = 7

i=7   j=10     k= ((7+10)/ 2)) = 8

i=8  j=10     k= ((8+10)/ 2)) = 9

i=9  j=10     k= ((9+10)/ 2)) = 9

and goes into infinite loop 

 

for correct output 

if a[k] < x then i:= k+1
else j:= k-1;

  

Position:
Show:

Related questions

78 78 votes
10 answers 10 answers
47.0k
47.0k views
Kathleen asked Oct 9, 2014
47,031 views
The average number of key comparisons required for a successful search for sequential search on $n$ items is$\dfrac{n}{2}$$\dfrac{n-1}{2}$$\dfrac{n+1}{2}$None of the abov...
37 37 votes
8 answers 8 answers
15.0k
15.0k views
Kathleen asked Oct 9, 2014
14,967 views
Let $G$ be the directed, weighted graph shown in below figureWe are interested in the shortest paths from $A$.Output the sequence of vertices identified by the Dijkstra’s...
37 37 votes
1 answers 1 answer
7.9k
7.9k views
Kathleen asked Oct 9, 2014
7,903 views
A complete, undirected, weighted graph $G$ is given on the vertex $\{0, 1,\dots, n -1\}$ for any fixed ‘n’. Draw the minimum spanning tree of $G$ ifthe weight of the edge...
39 39 votes
2 answers 2 answers
9.6k
9.6k views
Kathleen asked Oct 9, 2014
9,588 views
A two dimensional array $A[1..n][1..n]$ of integers is partially sorted if $\forall i, j\in [1..n-1], A[i][j] < A[i][j+1] \text{ and } A[i][j] < A[i+1][j]$The smallest it...