public class BinarySearch {
private static int search(int key, int[] a) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
int midVal = a[mid];
if (key < midVal) {
hi = mid - 1;
} else if (key > midVal) {
lo = mid + 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] list = {
100, 500, 300,
400, 200, 600,
900, 800, 700
};
int key = 500;
int result = search(key, list);
System.out.println(result);
}
}
当key = 100 or 200
可以输出0或4时,但是当我让key
等于或大于500时,程序总是输出-1。
Java版本:10.0.1