二分查找
2018-12-18 本文已影响0人
猴子扔飞镖
long[] a = {1, 2, 3, 4, 7, 3, 5, 10, 23, 89, 44};
int i = binarySearch(a, 4);
System.out.println(i);
public static int binarySearch(long[] a, long key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
long midVal = a[mid];
if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}