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

Trung Minh

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[5] = {5,4,3,2,1},num = 1,len = 5;
      int indx = recursive_binary_search(arr,num,0,len-1);
      printf("Index of %d is %d",num,indx);
      return 0;
}
A. Index of 1 is 4
B. Index of 1 is 5
C. Index of 1 is -1
D. Index of 1 is 0
 
Answer: C
Explanation: Since the array is sorted in descending order, the above implementation of binary search will not work for the given array. Even though 1 is present in the array, binary search won't be able to search it and it will produce -1 as an answer.
 

Tìm kiếm

Back
Top