0

I have a programme that calls a function, which in turn calls a recursive function.

How do you pass the result of the recursive function back to the main programme via the middle function?

Currently it will return either found or didn't find depending on how I structure the middle function. In this instance it would return 'found' every time. I know that the binary search function is working although there may be an error in what it is returning to the search function.

Call from main programme:

if (search(value, array, size))
{
    printf("\nFound!\n\n");
    return 0;
}
else
{
    printf("\nDidn't find.\n\n");
    return 1;
}

Search function:

bool search(int value, int values[], int n)
{
    if(binary_search(value, values, ((n - n) + 1), n))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Recursive function:

bool binary_search (int key, int array[], int min, int max)  
{   
    if (max < min)
    {
        return -1;
    }

    int midpoint = (min + max)/2;

    // {
    if (array[midpoint] > key)
    {
        return binary_search (key, array, min, midpoint-1);
    }

    else if (array[midpoint] < key)
    {
        return binary_search (key, array, midpoint+1, max);
    }

    else if (array[midpoint] == key)
    { 
        return midpoint;
    }

    else
    {
        return false;
    }
// }
}
12
  • 2
    You can, you know, return the value. And indent the code please. Commented Aug 10, 2015 at 19:24
  • 1
    You should not be returning -1 in a bool. Commented Aug 10, 2015 at 19:24
  • 1
    How about return binary_search(value, values, ((n - n) + 1), n) ? Commented Aug 10, 2015 at 19:24
  • 1
    Your bool binary_search() method is wrong, as it has return type which does not match the return type of the method. Such as : return -1 and return midpoint. Commented Aug 10, 2015 at 19:27
  • 2
    @G Spencer And why the initial minimum index is equal to 1? Commented Aug 10, 2015 at 19:34

1 Answer 1

2

Your binary_search function is not returning a boolean in all instances.

In the place where you return -1 you should instead return false. Similarly, where you return midpoint you should instead return true.

Edit:

As mentioned in Vlad's comment, you should be starting your search at 0 instead of 1, otherwise you won't find anything at the start of the list.

Sign up to request clarification or add additional context in comments.

2 Comments

That's not a very useful search if it only says "yes, it's here somewhere". Better to fix it to return int, which is either found index or -1.
@dbush His recursive function is wrong apart from the problem of the return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.