public static int binarySearch(int[] x, int target) {
int left = 0;
int right = x.length - 1;
int mid = (right + left ) / 2;
while ( left <= right) {
mid = (right + left) / 2;
if (x[mid] == target) {
return mid;
}
else if (x[mid] > target) {
right = mid-- ;
}
else if (x[mid] < target ) {
left = mid ++;
}
}
return -1;
}
say the code is:
` public static void main(String args[] ) {
int[] myArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println(binarySearch(myArr, 11));
}`
it never prints out -1, instead it goes in a loop where:
mid: 10
left: 9
right: 10
how can I fix this?
New contributor
jz9348 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.