0

I am struggling to implement the recursive binary search function: We are not supposed to change the search() declaration, so I thought I will have to implement a separate recursive function for binary search. I think my sort function works ok and my code for binarysearch() is correct and will return true (not posting it here), but it seems that isn't passed back to search and hence find always gets the message that the needle wasn't found. I am not sure how to better implement this, hope someone can point me in the right direction, please?

bool search(int value, int values[], int n)
{
    if (n <= 0)
    {
        return -1;
    }
    else
    {   
        int min = 0;
        int max = n - 1;
        return binarysearch(value, values, min, max);
    }
}
7
  • Just as a quick comment: If binarysearch() gets called by search() and truly returns true, then that means search() will also unconditionally return true, as it simply returns the returnvalue of binarysearch(). So either the function calling search() does not process the return properly, or you've made a mistake somewhere.
    – ZeroStatic
    Sep 12, 2014 at 7:43
  • Ok, so you're saying the code above should work as intended, right? I wasn't sure if I was calling binarysearch() correctly. Thanks a lot, that should help me narrow down the error, then. Since I didn't change the function calling search() in find.c, it must be in my binarysearch(), then.
    – Alexandra
    Sep 12, 2014 at 8:50
  • In theory yes, if you could add a pseudo-code version of your binarysearch implementation that would help a lot.
    – ZeroStatic
    Sep 12, 2014 at 9:38
  • Thanks to your help I have found the issue: I was calling the recursive function in the wrong way: '// search bottom half of list if (value < values[mid]) { max = mid - 1; binarysearch(value, values, min, max); }' The above was my initial way to call it, and after inserting return before binarysearch() I got it to work. Thanks again, guys!
    – Alexandra
    Sep 12, 2014 at 9:40
  • Then I guess the pseudo-code is no longer necessary, unless you get stumped by another different problem. Congratulations on finding out :)
    – ZeroStatic
    Sep 12, 2014 at 9:41

1 Answer 1

1

OK, so this was the code that didn't work in my recursive binarysearch():

// search bottom half of list  
if (value < values[mid])  
{      
    max = mid - 1;
    binarysearch(value, values, min, max);  
} 

And then, I changed it to return binarysearch() and now I'm good to go.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .