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?
You have done two mistakes 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);
}