I had trouble understanding this recursion.
I entered number “11”
When the binarySearch function is called it goes through this line of code to calculate mid:
int mid = l + (r-l) / 2;
when the function is called again the l and r values are changed but when I calculate it by hand the mid is always 6 but the mid always changes in the output. I don’t get it.
how can mid change to 6, 9, 11, 10
sample:
code:
#include <stdio.h>
#include <stdlib.h>
int binarySearch(int a[], int e, int l, int r); //e = element to look for, l = left indx, r = right index
int main() {
int num;
printf("Enter a number to find: ");
scanf("%d", &num);
int unsorted[] = {9,5,13,3,8,7,2,12,6,10,4,11,1};
int sorted[] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int index = binarySearch(sorted, num, 0, 12);
printf("%d found at index: %d", num, index);
return 0;
}
int binarySearch(int a[], int e, int l, int r) {
int mid = l + (r-l) / 2;
printf("l: %d\n", l);
printf("r: %d\n", r);
printf("mid: %d\n", mid);
if (l > r) return -1;
if(a[mid]==e)
return mid;
else if(a[mid] > e)
return binarySearch(a, e, l, mid-1); //1 to the left of the middle index
else if(a[mid] < e)
return binarySearch(a, e, mid+1, r); //look at the right portion, the l is now one to the right
}