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? It will run into an infinite loop when $x$ is not in $listA$. It is an implementation of binary search. It will always find the maximum element in $listA$. It will return −$1$ even when $x$ is present in $listA$. DS gatecse-2014-set3 data-structures array easy + – go_editor asked Sep 28, 2014 • edited Dec 16, 2017 by kenzou go_editor 13.6k views answer comment Share Follow See all 4 Comments See all 4 4 Comments reply Angkit commented Jun 12, 2017 reply Follow Share Why is ProcessArray called again,if it is a BINARY SEARCH? 0 votes 0 votes Manu Thakur commented Dec 31, 2017 reply Follow Share If someone believes that option (A) is also correct, then following is the counter example: Suppose listA={10, 20, 30, 40, 50} i=0; j=4; x = 60; k = (0+4)/2 = 2 listA[2] <= 60; hence i=k+1 = 3 k = (3+4)/2 = 3 listA[3]<= 60; Hence i = k+1 = 4; k = (4+4)/2 = 4 listA[4] <= 60, hence i=k+1 = 5 Now, i>j, so loop terminates and returns -1. 12 votes 12 votes Nain commented Sep 18, 2019 reply Follow Share It seems like option D is also correct 4 votes 4 votes KUSHAGRA गुप्ता commented Dec 27, 2019 reply Follow Share @Nain How you are getting that. Please provide an example. 1 votes 1 votes Please log in or register to add a comment.
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. Acharya Swaroop answered Mar 14, 2018 Acharya Swaroop comment Share Follow See all 0 reply Please log in or register to add a comment.
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 eliecher answered Jan 24, 2023 eliecher comment Share Follow See all 0 reply Please log in or register to add a comment.