Ok, so I'm given the function
int bin(int value, int size, int array[])
I am supposed to find "value" within "array[]", but the issue at hand here is that in most cases, we have something along the lines of
int bin(int value, int max, int min, int array[])
The recursion, logically, is a lot easier on this part due to the fact I can still pass the number I am at, as well as remember the size of the array.
int bin(int array[], int value, int min, int max)
{
if(max < min)
return -1;
else
{
int mid = min + (max - min)/2;
if(array[mid] > value)
return bin(array, value, min, mid-1);
else if(array[mid] < value)
return bin(array, value, mid+1, max);
else
return mid;
}
But since I can only pass 1 integer, how exactly would I adjust this algorithm for it? In essence, I would only be able to do something like this, but I KNOW it will not logically work. Is there a way, though, that I can see the size of the array? I tried it, but the numbers weren't crunching right.
int bin(int array[], int value, int size)
{
int mid = size/2;
if(array[mid] > value)
return bin(array, value, size-(size/2));
else if(array[mid] < value)
return bin(array, value, size+(size/2));
else
return mid;
}
You need to explicitly pass the base as well:
int
bin(int array[], int value, int size)
{
int mid = size/2;
if(array[mid] > value)
return bin(array, value, size/2);
else if(array[mid] < value)
return bin(&array[mid], value, size/2);
else
return mid;
}
note the "&array[mid] in the "if(array[mid] < value)" case
each time, you have the correct half of the array to search, using base + offset vice min/max indices
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With