I’m tryng to code a binary search method and it’s working properly but in more steps than expected.
I found that an if statement in while loop isn’t working even when the condition is printed, it’s true.
public class Main {
public static void main(String[] args) {
int element = 47;
int[] array = {1, 2, 3, 7, 8, 11, 12, 15, 47, 67, 879, 12345, 3463457, 367847884};
System.out.println(
(binarySearch(array, element) != -1) ?
("Element found at index: " + binarySearch(array, element)) :
"Element not found"
);
}
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
System.out.println(array[mid]);
System.out.println(target);
System.out.println(target==array[mid]);
System.out.println();
if (target == array[mid]) { //this isn't working
return mid;
}
if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
and the console:
12
47
false
879
47
false
47
47
true
12
47
false
879
47
false
47
47
true
Element found at index: 8
Process finished with exit code 0
in step 3 Referring to the console, value of target
and array[mid]
are the same.
why if (array[mid] < target) {left = mid + 1;}
isn’t working?