## java.util.Arrays helpers

No. 149

### Understanding search results

Q:

In Figure 431, “Arrays.binarySearch(...) the result reads:

sort|find(Mand): -3
sort|find(Mandy): 2
sort|find(Mandyer): -4
1. What does the positive value 2 in return to "Mandy" indicate?

2. Why do we get negative values -3 and -4 for "Mand" and "Mandyer" respectively?

3. What is the exact meaning of -3 and -4 besides being just negative?

### Tip

Read Arrays.binarySearch(...).

A:

The input array reads {"Aaron", "Eva", "Mandy", "Paul"}.

Array element Index
"Aaron" 0
"Eve" 1
"Mandy" 2
"Paul" 3
1. A positive value indicates an exact match: The string "Mandy" does exist within the array at index position 2.

2. A negative value indicates a value not being found: Both "Mand" and "Mandyer" do not exist in the array

3. The exact value of a negative integer being returned defines the hypothetical insertion position keeping the resulting array sorted. Regarding "Mandyer" the insertion index would be 3 squeezing "Paul" one step to the right:

   {"Aaron", "Eva", "Mandy", "Mandyer", "Paul"}
/* Index 0      1        2          3      4 /*



The observed return value of -4 when searching for "Mandyer" thus corresponds to insertion index 3. Hence we have the following rule:

Negate the return value and subsequently subtract 1.

Ratio: Subtracting 1 is being required for conveying the «not in list» information under all circumstances. Otherwise not finding and hypothetically inserting e.g. "A" at the list's beginning would result in 0. This could not be disambiguated from an array featuring an existing value"A" at its leftmost start position.