educative.io

Why is the answer -3?

Hi there,

In the array quiz question #3, why is the answer index -3? Since it’s searching for 4, and 4 is not in the array, shouldn’t it return the index of the next increment value (5 in this case), which is 2?

Thanks,
Nathan


Course: https://www.educative.io/collection/6650775272947712/6368023997317120
Lesson: https://www.educative.io/collection/page/6650775272947712/6368023997317120/5249193447260160

Hi @Nathan_Lin !!
In the case of the Arrays.binarySearch() method in Java, if the specified element is not found in the array, the method returns a negative value that represents the index at which the element would be inserted to maintain the sorted order of the array.

According to the documentation of the Arrays.binarySearch() method:

  • If the element is found, the method returns the index of the element.
  • If the element is not found, the method returns a negative value, which is the bitwise complement of the index where the element would be inserted.

In your example, the binarySearch() method is called with the array numbers and the target value 4. Since 4 is not present in the array, the method returns a negative value, specifically -3.

The negative value -3 indicates that if you were to insert the element 4 into the array while maintaining the sorted order, it would be inserted at index 2 (which is the bitwise complement of -3 minus one).

So, to answer your question, the result -3 does not represent the index of the next increment value. Instead, it indicates the position at which 4 should be inserted into the array to maintain the sorted order.
I hope it helps. Happy learning :blush: