On an assignment I had to make a recursive binary search algorithm output the index instead of True/False without modifying the parameters. I had a really tough time but after resorting to semi-trial-and-error I stumbled upon this mess:
#include <iostream>
#include <math.h>
#include <climits>
using namespace std;
int BinarySearch(int arr[], int len, int target) {
int temp = 0;
int mid = len/2;
if (len <= 0) return INT_MIN; // not found
if (target == arr[mid]){
return mid; // found
}
if (target < arr[mid]){
temp = BinarySearch(arr, mid, target);
}
else {
temp = mid+1 + BinarySearch(arr+mid+1, len-mid-1, target);
}
}
I have literally no idea why it works, even after running it through a visualizer. It's very sensitive to the code being changed and I can't get it to output -1 when it fails to find the target so I made it at least always output a negative number instead.
I don't really need it fixed, I just want to know how it even works since seemingly none of the recursive call's outputs are even used. Thanks.