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.

Jay Patel
  • 1,266
  • 6
  • 20
  • 38

2 Answers2

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..
hawkstrider
  • 4,141
  • 16
  • 27
-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

  • 3
    The question specifies "a sorted array **having distinct elements**" (emphasis mine); so neither of your test-cases is valid. – ruakh Jan 25 '19 at 21:24