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