In K&S Book it is given about unsuccessful Search like this .........
[[[[[[Unsuccessful searches return an int index that represents the insertion point.
The insertion point is the place in the collection/array where the element
would be inserted to keep the collection/array properly sorted. Because positive return values and 0 indicate successful searches, the binarySearch()
method uses negative numbers to indicate insertion points. Since 0 is a valid
result for a successful search, the first available insertion point is -1. Therefore,
the actual insertion point is represented as (-(insertion point) -1). For
instance, if the insertion point of a search is at element 2, the actual insertion
point returned will be -3.]]]]]
And in this I didn't get the formula .. (-(insertion point) -1). What it says. And I tried the following unsuccessful Searches....
Can you tell me how the above point can be related to this output ???
import java.util.*;
public class Ex {
public static void main(
String [] args) {
String [] sa = {"one", "two", "three", "four"};
Arrays.sort(sa); // #1
for(String s : sa)
System.out.print(s + " ");
System.out.print("\nfive = "
+ Arrays.binarySearch(sa,"five")); // result -1
System.out.print("\nsix = "
+ Arrays.binarySearch(sa,"six")); // result -3
System.out.print("\nseven = "
+ Arrays.binarySearch(sa,"seven")); // result -3
System.out.print("\nhex = "
+ Arrays.binarySearch(sa,"hex")); //result -2
}
}