数组搜索方法混乱
Arrays search method confusion
我对 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"));
}
}
当程序为运行时,它returns位置-4
。我在书上读到,它说,插入点表示为(-(insertionPoint)-1)
。为什么会这样?我无法理解这一点。
The insertion point is defined as the point at which the key would be inserted into the array.
{"one","two","three","four"}
排序为
{"four", "one", "three", "two"}
和throw
在three
之后。所以插入点将是 3
。结果是
(-(insertionPoint) -1) =
(-(3) -1) =
-4
我对 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"));
}
}
当程序为运行时,它returns位置-4
。我在书上读到,它说,插入点表示为(-(insertionPoint)-1)
。为什么会这样?我无法理解这一点。
The insertion point is defined as the point at which the key would be inserted into the array.
{"one","two","three","four"}
排序为
{"four", "one", "three", "two"}
和throw
在three
之后。所以插入点将是 3
。结果是
(-(insertionPoint) -1) =
(-(3) -1) =
-4