edited by
13,594 views
58 votes
58 votes

Consider the C function given below. Assume that the array $listA$ contains $n (>0)$ elements, sorted in ascending order.

int ProcessArray(int *listA, int x, int n)   
{     
        int i, j, k;     
        i = 0;     j = n-1;     
         do { 
               k = (i+j)/2;         
               if (x <= listA[k]) j = k-1;         
               if (listA[k] <= x) i = k+1; 
             }
        while (i <= j);     
        if (listA[k] == x) return(k);     
        else   return -1;   
}     

Which one of the following statements about the function $ProcessArray$ is CORRECT?

  1. It will run into an infinite loop when $x$ is not in $listA$.
  2. It is an implementation of binary search.
  3. It will always find the maximum element in $listA$.
  4. It will return −$1$ even when $x$ is present in $listA$.
edited by

10 Answers

0 votes
0 votes
When listA[k]=x;
then due to if(x<=listA[k]), j will be k-1
and due to if(listA[k]<=x), i will be k+1
thus, i>j because for every positive value of k, (k+1)>(k-1). So the loop will be terminated.
So it is a perfect working of Binary Search.
0 votes
0 votes

Consider : 

10 20 30 40 50

 

x=30
i 0 j 4 k ?
==iteration 1==
i 0 j 1 k 2
==iteration 2==
i 1 j 1 k 0
==iteration 3==
i 2 j 1 k 1
listA[k] = 20 != x
returns -1

but it can return the correct index sometimes

x = 20
i 0 j 4 k ?
==iteration 1==
i 0 j 1 k 2
==iteration 2==
i 1 j 1 k 0
==iteration 3==
i 1 j 0 k 1
listA[k] = 20 == x
returns 1

so the algorithm is partially correct

Answer:

Related questions

50 votes
50 votes
9 answers
1
go_editor asked Sep 28, 2014
16,551 views
Consider the following rooted tree with the vertex labeled $P$ as the root:The order in which the nodes are visited during an in-order traversal of the tree is$SQPTRWUV$$...