binarSearch:
第一钟形式: binaySearch(object [] a , object key)
对象数组a 表示要查找的数组元素 ,
对象数组key 表示 要查找的值
其中,a 表示要搜索的数组,key 表示要搜索的值。如果 key 包含在数组中,则返回搜索值的索引;否则返回 -1 或“-插入点”。插入点指搜索键将要插入数组的位置,即第一个大于此键的元素索引。
double[] score = {99.5, 100, 98, 97.5, 110, 95, 85.5, 100};如果要查找,先排序 用sort 方法 ,在排序
Arrays.sort(a);
现在来查找100,60的元素
import java.util.Arrays;
public class findarrss {
public static void main(String[] args) {
double[] score = {99.5, 100, 98, 97.5, 110, 95, 85.5, 100};
Arrays.sort(score);
for (double arr : score){
System.out.println(arr);
}
int index1 = Arrays.binarySearch(score, 100); // 否则返回 -1 或 “-插入点”。插入点指要将键插入数组的位置,即范围内第一个大于此键的元素索引。
int index2 = Arrays.binarySearch(score, 60); // 则返回 -1 或 “-插入点”。插入点指要将键插入数组的位置,即范围内第一个大于此键的元素索引。
System.out.println("查找到 110 的位置是:" + index1);
System.out.println("查找到 60 的位置是:" + index2);
}
}
执行上述代码,输出结果如下:
查找到 100 的位置是:5 查找到 60 的位置是:-3
binarySearch() 还有另一种常用的形式,这种形式用于在指定的范围内查找某一元素
第二钟方法:
binarySearch(Object[] a,int fromIndex,int toIndex,Object key);a 表示要进行查找的数组,fromIndex 指定范围的开始处索引(包含开始处),toIndex 指定范围的结束处索引(不包含结束处),key 表示要搜索的元素。
在使用 binarySearch() 方法的上述重载形式时,也需要对数组进行排序,以便获取准确的索引值。如果要查找的元素 key 在指定的范围内,则返回搜索键的索引;否则返回 -1 或 “-插入点”。插入点指要将键插入数组的位置,即范围内第一个大于此键的元素索引。
double[] score = {99.5, 100, 98, 97.5, 110, 95, 85.5, 100};如果要查找,先排序 用sort 方法 ,在排序
Arrays.sort(a);
现在来查找100,60的元素
import java.util.Arrays;
public class findarrss {
public static void main(String[] args) {
double[] score = {99.5, 100, 98, 97.5, 110, 95, 85.5, 100};
Arrays.sort(score);
for (double arr : score){
System.out.println(arr);
}
int index1 = Arrays.binarySearch(score, 2,6,100); // 否则返回 -1 或 “-插入点”。插入点指要将键插入数组的位置,即范围内第一个大于此键的元素索引。
int index2 = Arrays.binarySearch(score, 2,6,60); // 则返回 -1 或 “-插入点”。插入点指要将键插入数组的位置,即范围内第一个大于此键的元素索引。
System.out.println("查找到 110 的位置是:" + index1);
System.out.println("查找到 60 的位置是:" + index2);
}
}
执行上述代码,输出结果如下:
查找到 100 的位置是:5 查找到 60 的位置是:-3