n0hepe
n0hepe

Reputation: 188

Java binary search recursive

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.

Upvotes: 1

Views: 156

Answers (3)

Joffrey
Joffrey

Reputation: 37729

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.

Upvotes: 2

Richard Miskin
Richard Miskin

Reputation: 1260

There is no return where you have the recursive call to

searchBin

Upvotes: 1

Orel Eraki
Orel Eraki

Reputation: 12196

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);

Upvotes: 2

Related Questions