educative.io

We can skip the loop for finding the proper bounds

I wonder if we set the end of the array to the max value? I think the binary search can adjust the boundaries by itself, right?

public static int search(ArrayReader reader, int key) {
     int left = 0;
     int right = Integer.MAX_VALUE;
     while (left < right) {
       int mid = left + (right-left) / 2;
       if (reader.get(mid) < key){
          left = mid + 1;
       } else {
          right = mid;
       }
  }
  return reader.get(left) == key ? left : -1;
}

Hi @Dmytro_Paukov

If we follow your solution, we need to assume that the array is of size Integer.MAX_VALUE, but that’s not always the case. For example, consider scenarios where the size of the array is less than Integer.MAX_VALUE (say 100) or greater than Integer.MAX_VALUE.