Search code examples
javarecursionbinary-search

Why is return executed twice


In this case the value does match and the value of boolean is set to true,however return is called twice and does update the value to false.Can anyone suggest what am I missing here?.

public class BinSearch {

    public static void main(String[] args) {

        BinSearch bin=new BinSearch();
        int arr[]= {2,4,6,8,10,12,14,16};
        boolean b=bin.binSearch(arr,0,arr.length-1,12);
        System.out.println("Number found "+b);

    }

    public  boolean binSearch(int arr[],int low,int high,int val)
    {
        int mid=(low+high)/2;

        if(arr[mid]==val)
        {
            return true;
        }

        else if(arr[mid]>val)
        {
            binSearch(arr,mid+1,high,val);
        }

        else  
        {
            binSearch(arr,low+1,mid,val);
        }

        return false;
    }
}

Solution

  • You're missing two returns when calling the recursion:

    return binSearch(...);
    

    If you don't write them, the method will ignore the result of the recursion and just return false at the end. After doing that, the last return will be unnecessary and should be deleted. Finally, you need to check the case when low > high, that means that the element was not found.