Search code examples
javarecursionbinarybinary-search

Variable declaration in BinarySearch


I am working on a java project BinarySearch. I'm trying to create and initialize a variable mid which will find out the middle value but it is giving me an error that you can't declare a variable here. I also tried it with the split declaration but it didn't work. Here is my piece of code:

 public static boolean binarySearch(int[] data, int target, int low, int high){
        if(low>high)
            return false;
        else
            int mid=(low + high )/2;
        if(target==data[mid]);
            return true;
        else if(target<data[mid])
            return binarySearch(data, target, low, mid - 1);
        else
            return binarySearch(data, target, mid + 1, high);


    }

What should I do to solve this problem?


Solution

  • You have done two mistakes here.

    • First you have to declare mid variable in the beginning, since it using in other scopes too (Not only in else scope).
    • Second one is you have to remove the semicolon here if(target==data[mid]);. Since it's terminating the line.

    Code after fixing those issues,

    public static boolean binarySearch(int[] data, int target, int low, int high){
      int mid;
      if (low > high)
        return false;
      else
        mid = (low + high) / 2;
      if (target == data[mid])
        return true;
      else if (target < data[mid])
        return binarySearch(data, target, low, mid - 1);
      else
        return binarySearch(data, target, mid + 1, high);
    }