【原】Arrays.binarySearch() 的用法
Arrays.binarySearch() 的用法
1.binarySearch(Object[] a, Object key)
Searches the specified array for the specified object using the binary search algorithm.
参数1:a是要查询的数组;参数2:key是要查询的关键字;返回值是key所在数组的索引值,如果没有找到就返回-1
注意:该数组必须是升序排列的
2.查看具体源代码:
private static int binarySearch0(Object[] a, int fromIndex, int toIndex,
Object key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
Comparable midVal = (Comparable)a[mid];
int cmp = midVal.compareTo(key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
3.自己写例子使用
import java.util.Random;
public class Test {
public static void main(String[] args) {
Object[] a = new Object[1000];
for(int i=0;i<a.length;i++){
Integer myint = i+1;
a[i]=myint;
}
Integer key = new Random().nextInt(a.length);
int keyindex = mybinarySearch0(a,0,a.length,key);
if(keyindex>=0)
System.out.println("找到的key:"+a[keyindex]);
}
private static int mybinarySearch0(Object[] a, int fromIndex, int toIndex,
Object key) {
int low = fromIndex;
int high = toIndex - 1;
//这也是为什么数组必须升序排列的
while (low <= high) {
//>>> 无符号右移,高位补0,这里相当于/2
int mid = (low + high) >>> 1;
Comparable midVal = (Comparable) a[mid];
int cmp = midVal.compareTo(key);
System.out.println(midVal+".compareTo("+(key)+")");
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
}
4.运行结果