+ 1

Problem with binary search code.

Whenever target is greater then max element same error occurs. Code : public class newcode { static int binarySearch(int[] arr, int target){ int start = 0; int end = arr.length; while (start<=end){ int mid = start+(end-start)/2; if (target<arr[mid]){ end = mid-1; } else if (target>arr[mid]) { start = mid+1; } else { return mid; } } return -1; } public static void main(String[] args) { int[] arr = {1,3,6,7,9,18}; System.out.println(binarySearch(arr, 20)); } } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6 at newcode.binarySearch(newcode.java:9) at newcode.main(newcode.java:21) Process finished with exit code 1

23rd Jun 2023, 10:36 AM
Ayush Kumar
Ayush Kumar - avatar
2 odpowiedzi
+ 5
Try replacing "<=" with "<" in the line 6: "while(start<=end){}"? This raises IndexOutOfRangeException becuz array index starts at 0, your array length is 6, and the last index is 5. You are trying to get the elements of a index that doesn't exist.
23rd Jun 2023, 10:46 AM
Dragon RB
Dragon RB - avatar
+ 1
You should read the error, this will help you to find where you made a mistake and fix it! Good luck.
5th Jul 2023, 5:25 PM
Dragon RB
Dragon RB - avatar