Method Arrays.binarySearch() - Quiz

Total: 5 questions

1. 

What is the key requirement for the array before calling Arrays.binarySearch()?

The array must be sorted in ascending order (usually with Arrays.sort()). For an unsorted array the result is undefined: no exception is thrown, but the method may return a meaningless value. If a comparator is used, the array must be ordered by that same comparator.

2. 

What does Arrays.binarySearch() return when the element is not found, and what is the insertion point?

It returns a negative number computed as -(insertionPoint) - 1. The insertion point is the index of the first element greater than the search key — the position where the element could be inserted while keeping the array sorted. You can recover it from the result with -result - 1. The offset of one exists to distinguish "not found, insertion point 0" (result -1) from "found at index 0" (result 0).

3. 

How do you search only a part of the array with Arrays.binarySearch()?

Use the overload with fromIndex and toIndex: binarySearch(array, from, to, key). The start index is inclusive and the end index is exclusive (the half-open range [from, to)). It is this range that must be sorted. The returned index is a position in the original array, not relative to the start of the range.

4. 

How does Arrays.binarySearch() compare elements in an object array, and when is a Comparator needed?

The overload binarySearch(Object[] a, Object key) uses the natural ordering — the elements must implement Comparable (like String or Integer). If the array is sorted in a non-natural order (for example, descending), use the overload binarySearch(T[] a, T key, Comparator<? super T> c) and pass the same comparator that was used for sorting.

5. 

What are the common mistakes when working with Arrays.binarySearch()?

The main pitfalls: (1) searching an unsorted array — the method does not check the order and may return a wrong result without throwing; (2) relying on duplicates — with several equal values there is no guarantee which index is returned (not necessarily the first); (3) a comparator that does not match the sort order; (4) checking if (result == -1) instead of result < 0 — comparing to -1 catches only the "insertion point 0" case; (5) searching for null or objects without Comparable leads to a NullPointerException or ClassCastException.

Page 1 of 1