3

I am given a sorted array having distinct elements.

Return true if A[i] = i

else return false;

I am required to just return true or false, and not the position.

I have implemented the code, but there is some minor bug.

private static boolean find(int[] a, int low, int high) 
{
    System.out.println(Arrays.toString(a)+" "+low+ " "+high);
    if(low<=high)
    {
        int mid = (low+high)/2;

        if(mid==a[mid])
        {
            return true;
        }
        else if(a[mid]>mid)
        {
            find (a,low,mid-1);
        }
        else{
            find (a,mid+1,high);
        } 

    }

    return false;


}

I know it reaches return false even if it has found the mid.

What changes should I make so that it returns true in all cases.

2 Answers 2

5

Where you are recursively calling find, you should have a return before calling find so that it will return the result of the nested call

return find(...) //etc..
Sign up to request clarification or add additional context in comments.

1 Comment

Oh My God.. Thanks :D
-1

Your code have the bug !!

check for testcase0: [1,1,2,3,4,5,6,7]and testcase1 = [1,2,3,4,5,6,6] Your code works for testcase1 and not for testcase0

Because for testcase1, mid is 3 and 4 > 3 and then you skip the [5,6,6] which contaions the answer !!!! Hope it will help

1 Comment

The question specifies "a sorted array having distinct elements" (emphasis mine); so neither of your test-cases is valid.

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.