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?

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? Correct Answer It is an implementation of binary search.

Explanation:

Suppose Array A:

3

4

5

7

 

n= 4 and suppose x = 5

i=0  and j = n-1 = 3

Inside 1st  do while loop: 

k = 3 divide with 2 = 1

1st if condition : (5<=listA ) = ( 5 <= 4)  condition false

2nd if condition : 4<= 5 condition true so now i = k+1 = 2

while (2<=3) condition true

2nd do while loop:

k= 5 divide with 2 = 2

1st if condition : 5<=5 condition true j= k-1= 2-1 = 1

2nd if condition: 5<=5 condition true i= k+1 =2+1=3

while(3<=1) condition true

Outside do while loop:

If condition is true and return k = 2

 

If we carefully observe this is nothing but binary search implementation where we are finding element x in listA and return index of that element if it is present in listA array.

Related Questions

A teacher asked the class to subtract 5 from 75.70% of the class said: 25. Their work was shown as: \(\begin{array}{*{20}{c}} {\begin{array}{*{20}{c}} 7&5 \end{array}}\\ {\underline {\begin{array}{*{20}{c}}\ { - 5} \ \ \ &{} \end{array}} }\\ {\underline {\begin{array}{*{20}{c}} 2&5 \end{array}} } \end{array}\) Which of the following describes the most appropriate remedial action that the teacher should take to clarify this misconception?