写了一段代码测试了一下
public class BinarySearch {
static Map<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) {
int[] a = new int[30];
for (int i = 0; i < a.length; i++) {
a[i] = i + 1;
}
for (int i = 0; i < a.length; i++) {
binarySearch(a, a[i]);
}
for (Map.Entry entry : map.entrySet()){
if (entry.getValue() == (Integer)5){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
static Map<Integer, Integer> binarySearch(int[] a, int key){
int low = 0;
int high = a.length - 1;
int compTimes = 0;
while (low <= high) {
++compTimes;
int mid = (low + high) / 2;
if (a[mid] == key){
map.put(key, compTimes);
return map;
}else if (a[mid] > key){
high = mid - 1;
}else {
low = mid + 1;
}
}
return null;
}
} 输出结果为:
2:5
4:5
6:5
8:5
10:5
12:5
14:5
16:5
18:5
20:5
22:5
24:5
26:5
28:5