假设:
import java.util.*;
public class Quest
{
public static void main(String[] args) {
String[] colors = {"blue", "red", "green", "yellow", "orange"};
Arrays.sort(colors);
int s2 = Arrays.binarySearch(colors, "orange");
int s3 = Arrays.binarySearch(colors, "violet");
System.out.println(s2 + " " + s3);
}
}
输出为2 -5
。为什么呢?
答案 0 :(得分:6)
2是排序数组中的橙色索引(因此它是第三个元素)。
-5是-insertion_point - 1.插入点是可以插入密钥的位置,并且数组保持排序。
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#binarySearch(int [],int)
答案 1 :(得分:4)
(新)排序数组看起来像这样:
0 1 2 3 4
"blue", "green", "orange", "red", "yellow"
2
是元素"orange"
(-4 - 1) = -5
"violet"
的插入点位于索引4
("red"
后面)进一步阅读