binarySearch(Object[] a,Object key);其中,a 表示要搜索的数组,key 表示要搜索的值。如果 key 包含在数组中,则返回搜索值的索引;否则返回 -1 或“-插入点”。插入点指搜索键将要插入数组的位置,即第一个大于此键的元素索引。
public static void main(String[] args) {
double[] score = { 99.5, 100, 98, 97.5, 100, 95, 85.5, 100 };
Arrays.sort(score);
int index1 = Arrays.binarySearch(score, 100);
int index2 = Arrays.binarySearch(score, 60);
System.out.println("查找到 100 的位置是:" + index1);
System.out.println("查找到 60 的位置是:" + index2);
}
执行上述代码,输出结果如下:
查找到 100 的位置是:5 查找到 60 的位置是:-1
binarySearch(Object[] a,int fromIndex,int toIndex,Object key);其中,a 表示要进行查找的数组,fromIndex 指定范围的开始处索引(包含开始处),toIndex 指定范围的结束处索引(不包含结束处),key 表示要搜索的元素。
public static void main(String[] args) {
double[] score = {99.5,100,98,97.5,100,95,85.5,100};
Arrays.sort(score);
int index1 = Arrays.binarySearch(score,2,6,100);
int index2 = Arrays.binarySearch(score,2,6,60);
System.out.println("查找到 100 的位置是:"+index1);
System.out.println("查找到 60 的位置是:"+ index2);
}
执行上述代码,输出结果如下:
查找到 100 的位置是:5 查找到 60 的位置是:-3
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有