1

I have to implement Binary search method which finds if value is or isn't in array. I have to use recurse.

public static boolean searchBin(int[] array, int x, int l, int r) {

        int center;

        center =(l+r) / 2;
        if ( x > array[center] )
        {
            l = center+1;
        }   
        else 
        {
            r = center-1;
        }

        if ( array[center] == x )
        {
            return true;
        }
        else
        {
            if ( l<=r )
            {
                searchBin(array,x,l,r); 
            }
            else
            {
                return false;
            }
        }
    }

I'm getting the following error:

Missing return statement

Thanks.

2
  • Because there exists a path on which you don't return anything. But the method should return something.. Commented Feb 27, 2014 at 20:36
  • 1
    Shouldn't it be return searchBin(array,x,l,r); ? Commented Feb 27, 2014 at 20:37

3 Answers 3

2

This is because as the error suggests "not all paths return a value".

This is the possible problem:

searchBin(array,x,l,r);

A fix will be:

return searchBin(array,x,l,r);
Sign up to request clarification or add additional context in comments.

Comments

2

This is because one of the possible path of execution could lead to none of your return statements: in the last if, if the condition l<=r is true, nothing is returned (you only call recursively your method).

You might want to add the return keyword before your recursive call:

return searchBin(array,x,l,r);

This way, your method will (in this case) return whatever the recursive call returns.

Comments

1

There is no return where you have the recursive call to

searchBin

Comments

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.