Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search Recursion Algorithm Issue In C

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;
    }
like image 408
Ezrb3zr Avatar asked Dec 11 '22 23:12

Ezrb3zr


1 Answers

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

like image 158
tbert Avatar answered Dec 21 '22 08:12

tbert