二分查找之Arrays.binarySearch

首先,binarySearch方法为二分法查找,所以数组必须是有序的或者是用sort()方法排序之后的

binarySearch(Object[], Object key)
 
方法的object[]参数是要查找的数组,key参数为要查找的key值。
 
 
方法的返回值有几种:
 
1.找到的情况下:如果key在数组中,则返回搜索值的索引。
 
2.找不到的情况下:
 
 [1] 搜索值不是数组元素,且在数组范围内,从1开始计数,得“ - 插入点索引值”;
 [3] 搜索值不是数组元素,且大于数组内元素,索引值为 – (length + 1);
 [4] 搜索值不是数组元素,且小于数组内元素,索引值为 – 1。
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarySearch(a, 5);
int x2 = Arrays.binarySearch(a, 4);
int x3 = Arrays.binarySearch(a, 0);
int x4 = Arrays.binarySearch(a, 10);
结果为:x1=-4      x2=2    x3=-1    x4=-7

posted @ 2019-02-12 16:45  过山车  阅读(977)  评论(0编辑  收藏  举报