1 Answers

Option 2 : 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.

4 views

Related Questions