How would I do a binary search using recursion?
Problem in First question
hello @udatta
// Recursive implementation of the binary search algorithm to return
// the position of target `x` in subarray `A[low…high]`
int binarySearch(int A[], int low, int high, int x)
{
// Base condition (search space is exhausted)
if (low > high) {
return -1;
}
// find the mid-value in the search space and
// compares it with the target
int mid = (low + high)/2;
// Base condition (target value is found)
if (x == A[mid]) {
return mid;
}
// discard all elements in the right search space,
// including the middle element
else if (x < A[mid]) {
return binarySearch(A, low, mid - 1, x);
}
// discard all elements in the left search space,
// including the middle element
else {
return binarySearch(A, mid + 1, high, x);
}
}
logic is same , ie, check mid value if it is equal then return that index otherwise move left or right as per key
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.