Reputation: 199
public class ArrayUtilities {
public static void main(String[] args) {
int[] array1 = { 1, 2, 3, 4, 5, 10, 15, 30, 32 };
int target1 = 30;
System.out.println(binarySearch(array1, target1));
}
public static boolean binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (right >= left) {
int middle = (right - left) / 2;
if (target == array[middle]) {
return true;
} else if (target > array[middle]) {
left = middle - 1;
} else if (target < array[middle]) {
right = middle + 1;
}
}
return false;
}
}
Whenever i run the code, it doesnt print anything and it does not say error neither. I dont understand why. Please help! Thank you in advance.
Upvotes: 0
Views: 1212
Reputation: 4703
The algorithm is not implemented correctly;
Your code is running an infinite loop.
Places to consider:
int middle = (right - left)/2;
should beint middle = (right + left)/2;
else if (target > array[middle]){ left = middle - 1; should be
left = middle+1;
remember, you need to find the number in the next part of the array.Similarly consider the logic here; else if (target < array[middle]){ right = middle + 1; }
Upvotes: 1