Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 974
user7258708 Avatar asked Mar 28 '26 17:03

user7258708


1 Answers

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.

like image 141
Óscar López Avatar answered Mar 30 '26 05:03

Óscar López