0
static int binarySearch(int[] arr, int target){
        int start = 0;
        int end = arr.length -1;
        while(start<= end){
            //find the middle element
//            ind mid = (start + end )/2; // might be possible that the ( start+ end ) exceeds the range of int in java if they are very large values
            int mid = start + (end -start)/2 ; //same thing but this time it will not  exceed the int value
            if(target<arr[mid]){
                end = mid -1;
            }else if(target > arr[mid]){
                start = mid +1;
            }else{
                return mid;
            }

        }
        return -1;
    }
}

What's the need of writing int end = arr.length - 1 and why not int end = arr.length if we want to get the end of the array in binary search in java.

2 Answers2

1

Indexing for Java arrays starts with 0. So, if you define an arr[10], it has elements arr[0] to arr[9]. Your binary search algorithm accesses these elements for comparison, and trying to access arr[10] would be invalid, resulting in an IndexOutOfBoundsException.

PHolzwarth
  • 327
  • 1
  • 5
0

Because array starts on 0, so their last position is always their length minus 1. The array position "length" will be always out of range (an IndexOutOfBoundsException).