0
I want to find the value x from two array, but something wrong is going on in my code. Can someone help me
3 Answers
+ 2
This from your binarySearch function is very weird. What are you searching for? The x or 15 isn't passed to binarySearch and you don't compare with 15 anywhere. You just compare the sum of 2 elements with 0 here:
int sum = arr[l] + arr[r];
if(sum == 0)
return true;
The following implements binarySearch as a binary search algorithm and should do what you expect.
Some changes are:
- the following has a target or a needle to find. This is needed for any kind of search. Notice the extra "target" parameter in binarySearch method.
- the following narrows search interval in halfs every time until finding the target or failing to find it. Splitting the range in half is why it is called binary.
Here's the code:
public class Program
{
public static void main(String[] args) {
int arr1[] = {-10, -9, 1, 3, 8, 9, 11};
int arr2[] = {-10, -6, -4, 1, 3, 12, 14, 15};
int x = 15;
if (binarySearch(x, arr1, 0, arr1.length-1))
System.out.println(x + " Exists in array1");
else
System.out.println(x + " Doesn't Exists in array1");
if (binarySearch(x, arr2, 0, arr2.length-1))
System.out.println(x + " Exists in array2");
else
System.out.println(x + " Doesn't Exists in array2");
}
public static boolean binarySearch(int target, int arr[], int l, int r){
int mid = (l + r) / 2;
if(arr[mid] == target)
return true;
else if (r <= l)
return false;
else if(arr[mid] > target)
return binarySearch(target, arr, l, mid - 1);
else
return binarySearch(target, arr, mid + 1, r);
}
}
0
hanan code:
int arr1[] = {-10, -9, 1, 3, 8, 9, 11};
int arr2[] = {-10, -6, -4, 1, 3, 12, 14, 15};
l, r, sum
-10 11 1
-10 9 -1
-9 9 0
15 Exists in array1
-10 15 5
-10 14 4
-10 12 2
-10 3 -7
-6 3 -3
-4 3 -1
1 3 4
1 1 2
1 -4 -3
15 Doesn't Exists in array2