使用while的方式进行查找
public static int binarySearch(int[] a, int key) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (key < a[mid]) high = mid - 1;
else if (key > a[mid]) low = mid + 1;
else return mid;
}
return -1;
}
递归方案二分法
public static int binarySearch(int[] a, int start, int end, int key) {
int mid = (end + start + 1) / 2;
if (key > a[end] || key < a[start] || a[start] > a[end]) return -1;
if (key == a[mid]) {
return mid;
} else if (key > a[mid]) {
return binarySearch(a, mid + 1, end, key);
} else if(key < a[mid]) {
return binarySearch(a, start, mid - 1, key);
}
return -1;
}