What is the output of the following code? [code] #include<stdio.h> int recursive_binary_search(int *arr, int num, int lo, int hi) {

Tiên Hương

New member
What is the output of the following code?
Code:
#include<stdio.h>
int recursive_binary_search(int *arr, int num, int lo, int hi)
{
      if(lo > hi)
       return -1;
      int mid = (lo + hi)/2;
      if(arr[mid] == num)
       return mid;
      else if(arr[mid] < num)
          lo = mid + 1;
      else
          hi = mid - 1;
      return recursive_binary_search(arr, num, lo, hi);
}
int main()
{
      int arr[8] = {0,0,0,0,3,5,6,7},num = 0,len = 8;
      int indx = recursive_binary_search(arr,num,0,len-1);
      printf("Index of %d is %d",num,indx);
      return 0;
}
A. Index of 0 is 0
B. Index of 0 is 1
C. Index of 0 is 2
D. Index of 0 is 3
 
Answer: D
Explanation: In this case, when the function recursive_binary_search() is called for the first time we have: lo = 0 and hi = 7. So, the value of mid is:
mid = (lo + hi)/2 = (0 + 7)/2 = 3. Since, arr[mid] = arr[3] = 0, the function returns the value of mid, which is 3.
 

Tìm kiếm

Back
Top