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.