educative.io

Why not check mid+1 within bounds?

In the implementation, it didn’t check mid +1 is < arr.length-1; how could it make sure mid+1 is not out of Bounds? Thanks.

public static int findMax(int[] arr) {
int start = 0, end = arr.length - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (arr[mid] > arr[mid + 1]) {
end = mid;
} else {
start = mid + 1;
}
}

2 Likes

Explanation here might help

I’d like to know the same thing. I would think you need to check the bounds.

Only potential reason for not checking would be, that we are stoping iteration when start == end. Meaning the smallest window we could have would be when start and end point to indices immediately next to one another. In the case that end points to the last element in the array and start points to the element before that, middle would always evaluate to the start index position, meaning mid+1 would never be out of bounds. At that point, start == end and we terminate.