Reputation: 4629
I am confused about Arrays.binarySearch(Object[], Object)
.
public class SearchObjArray {
public static void main(String[] args){
String[] sa = {"one","two","three","four"};
Arrays.sort(sa);
for(String s : sa ){
System.out.println(s + " ");
}
System.out.println("\n one = " + Arrays.binarySearch(sa,"thro"));
}
}
When the program is run, it returns position -4
. I was reading in the book, it states that, insertion point is represented as (-(insertionPoint)-1)
. Why it is like this? I am not able to grasp this point.
Upvotes: 0
Views: 34
Reputation:
The insertion point is defined as the point at which the key would be inserted into the array.
{"one","two","three","four"}
sorted is
{"four", "one", "three", "two"}
and throw
comes after three
. So the insertion point would be 3
. The result thus is
(-(insertionPoint) -1) =
(-(3) -1) =
-4
Upvotes: 5