Binary search recursing issue

I've been working on a binary search of pset3 find, and I'm having an issue when I call the function again recursively. I believe that I know what the issue is, I'm just not sure how to fix it. When I call the function, it resets the values of low mid and high, because they are in the function. I tried to make a new function inside that one, but you can't declare a function there. What I need to do is to make the called function start after I declared the variables the first time, so I don't create an infinite loop just re-declaring everything. Please help me fix this problem, my code is:

`bool search(int value, int values[], int n) { if (value < 0) { return false; } int low = values[0]; int high = values[n - 1]; int mid = (low + high) / 2; //printf("Low: %i Mid: %i High %i\n", low, mid, high); if (mid == value) { return true; }

``````else if (mid < value) {
low = mid;
mid = (low + high) / 2;
}

else {
high = mid;
mid = (low + high) / 2;
}

//printf("Low: %i Mid: %i High %i\n", low, mid, high);
check(low, mid, high, value);
//TODO: implement a searching algorithm
``````

}`

1 Answer

Well, you can declare a function in the very top before main like `check(int low, int mid ...);` and then define it somewhere in the bottom after main and then you can use it inside `bool search` after variable declaration. However:

What do you actually want to pass to this function? `check (low, mid, high, value)` ? How can it search something if you just pass just 4 int? Indeed, this new function would know nothing about values[].

You need to divide your initial array by half and then pass one half to recursion function, as well as value.

You may do it by creating new function and passing to it `value` , `values[]` , new size, and new [min] or new [max] defining which half of `values[]` recursive function should use.

Otherwise, you may proceed without declaration of new function, but then you need to copy half of `values[]` to new array of half size and pass it recursively to `search(value, new values[], new size)`.