I don’t know why this method is throwing an ArrayIndexOutOfBounds exception.
When I change the initial "high" value to "int high = array.length - 1;", the program will return any integer value that I search for.
What am I doing wrong?
Thanks in advance!
public class BinarySearch {
public static void main(String[] args) {
int searchValue = 12;
int[] givenNums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
binarySearch(givenNums, searchValue);
System.out.println("\nResult: " + searchValue);
}
public static int binarySearch(int[] array, int key) {
int low = 0;
int high = array.length;
int mid = (low + high) / 2;
int i = 0;
System.out.println();
while (low <= high) {
System.out.print(i + " ");
if (array[mid] < key) {
low = mid + 1;
mid = (low + high) / 2;
} else if (array[mid] > key) {
high = mid - 1;
mid = (low + high) / 2;
}
else
return mid;
i++;
}
return -1;
}
}
You need to be consistent about whether
highmeans the maximum value it can be inclusively or exclusively. You start off with it being an exclusive upper bound:But then your
whileloop condition is only appropriate if it’s an inclusive upper bound:You should probably just change the
whilecondition to:… and change the assignment of
highlater, too.Alternatively, you could keep it inclusive, and change the initial value to
array.length - 1.That will stop the situation where
low == high == mid == array.length, which is where it would blow up.I’d also suggest moving the
mid = (low + high) / 2computation to be the first statement within thewhileloop – then you can get rid of the duplicate code.