java - Why does my binary search produce an ArrayIndexOutOfBoundsException? -
i using eclipse. code:
private int binarysearch(int[] arraysorted, int value, int min, int max) { if (max < min) { return -1; } else { int mid = min + max / 2; if (value > arraysorted[mid]) // line 22 return binarysearch(arraysorted, value, mid + 1, max); else if (value < arraysorted[mid]) return binarysearch(arraysorted, value, min, mid - 1); else return mid; } }
and error:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 7 @ launcher.binarysearch(launcher.java:22) @ launcher.binarysearch(launcher.java:23) @ launcher.main(launcher.java:14)
i call method so:
int[] arraysorted = { 0, 1, 2, 2, 4, 7, 99 }; binarysearch(arraysorted, searchnum, 0, arraysorted.length - 1);
can figure out why getting this? how can identify issue using debugger?
the middle index element calculated incorrectly because of missing parentheses.
it should be:
int mid = (min + max) / 2;
and not
int mid = min + max / 2;
which calculates, adding unnecessary parentheses, min + (max / 2)
.
you can find out problem doing step-by-step analysis of code favorite debugger.
Comments
Post a Comment