Search code examples
javabinary-search

what is wrong in my code? Can someone help me


   public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {10,20,30,40,50,60,70,80};
        int index = search(arr,80,0,arr.length-1);
        if(index == -1) {
            System.out.println("element not found");
        }
        else {
            System.out.println("element is present at index:"+index);
        }
    }

    public static int search(int[] arr,int x,int start, int end) {

        if(start>end) {
            return -1;
        }
        int mid = (int)(Math.floor(start+end)/2);

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

        else if(arr[mid]>x) {
            search(arr,x,start, (mid-1));
        }

        else {
            search(arr,x, (mid+1),arr.length-1);
        }

        return -1;
    }
 }

As we can see that i am searching for 80 & my code is hitting the statement return mid; but still the program is returning -1. Can someone please tell what i am doing wrong here.


Solution

  • As stated, you are missing the return statements, and by that ignoring all returned values, also you need to use end instead of the array length in the else statement do this:

    else if(arr[mid] > x) 
    {
         return search(arr, x, start, (mid - 1));
    } else {
         return  search(arr, x, (mid + 1), end);
    }
    

    also a better way to calculate the mid is by:

    int mid = start + (end - start) / 2;
    

    To avoid integer overflow.