Variable declaration in BinarySearch

Viewed 60

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?

3 Answers

when you declare a variable in a block, you cant access to it from out the block, you should to decalre the variable out of the if and change him in the if, then, when you access it with target==data[mid] the program will know where to get it. for example:

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);


}

for more info about Variable Scope: Scope of Variables In Java

The issue is you're declaring it inside the else, which immediately falls out of scope and the value is lost

You can avoid the issue by declaring it outside of that scope (before the if statement), or by removing the else

if(low>high)
    return false;
int mid=(low + high )/2;

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);
}
Related