Well, when you are specifying the return type of a function, the function indeed expected to return some value when the control-flow left out from the function.
so a function, int function()
is expected to return a value of type integer, that's the standard.
Now, coming to your program, you have divided the array into two halves, and again in two halves from one of the halve created by the previous call, and continuously you are doing so, until and unless either you have found the value or you have exhausted all halves (which are valid, in terms of binary search).
Let's understand it thoroughly:
Let's say you have an array {1, 2, 3, 4, 5, 6, 7} and key {2}
so in terms of binary search, since the middle of the array which is 4
is the not element you are looking for, you would split the array into two halves and you would consider the left subarray since the middle{4} was greater than the element you are searching:
left_sub_array = {1,2,3,4} and right_sub_array = {5, 6, 7}
Again you would do the same thing, and you would stop and return the key/index, because:
since the middle of the current subarray {1,2,3,4} is 2, is the value you are looking for{2}.
Let's follow the control-flow again,
*first instance*
| int binarysearch(int * array, int arrlen, int key ){
| ...split the array by middle index and call second instance of the function "binarysearch"
| }
*second instance*
| int binarysearch(int * array, int arrlen, int key){
| ... got the element and return the value to first instance of the function "binarysearch"
|}
so you can now understand, for every self-call, we are creating an instance of the function and return a value (either result or not a result) when we got the result or come into the base condition.
The same thing is happening in your code too:
if(a[mid] < x){
return binarySearch(a, size, x, mid+1, high);
}
else{
return binarySearch(a, size, x, low, mid-1);
}
but to understand it better, let's store the value of the returned result into a variable and return the variable at the time of success (when key is found) or failure (when base case reached, key is not found).
int binarySearch(int a[], int size, int x, int low, int high){
int result = -1;
if(low > high) return -1;
int mid = (low + high)/2;
if(a[mid] == x){
return mid;
}
if(a[mid] < x){
result = binarySearch(a, size, x, mid+1, high);
}
else{
result = binarySearch(a, size, x, low, mid-1);
}
return result;
}
So you can see we are creating a variable result
for each instance of the function and store the returned value of the next instance into the variable, and continue doing so till the end (success/failure) and return the variable.