I’ve found the following code online,
int binary_search(int a[], int low, int high, int target) {
if (high < low)
return -1;
int middle = (low + high)/2;
if (target < a[middle])
return binary_search(a, low, middle-1, target);
else if (target > a[middle])
return binary_search(a, middle+1, high, target);
else if (target == a[middle])
return middle;
}
My function has a specified prototype(meaning that it has a set number of arguments that cannot be altered) this is what I have so far
bool search(int value, int array[], int n) {
if (array[n/2] == value)
return 1;
else if (array[n/2] < value)
return search(value, &array[n/2], (n)/2);
else
// how do I "return" the other half?
}
Does my implementation look correct so far? I can’t seem to figure out how to implement the final else statement.
high and low represent the bounds of subarray in which continue the research. If you analyze the code you’ll notice that if
targetis smaller thata[middle]you’ll have to continue the research in the first half of the array (in fact it calls binary_search passing the same low bound but, as a superior bound, the actualmiddle-1). On the other side, iftargetis greater thata[middle]you’ll have to continue the research in the second half of the array (frommiddle+1 tohigh). Of course, iftargetis equal toa[middle]you’ve finished.