public class 二分法 {
static int count;
public static void main(String[] args) {
// 在一个数组中查找一个数的下标:
int[] arr = {1, 3, 4, 7, 9, 11};
System.out.println(binarySearch(arr, 3));
System.out.println(count);
}
public static int binarySearch(int[] arr, int target) {
if (arr.length < 1) {
throw new RuntimeException("数组有误");
}
if (target < arr[0] || target > arr[arr.length - 1]) {
count++;
return -1;
}
if (target == arr[0]) {
count++;
return 0;
}
if (target == arr[arr.length - 1]) {
count++;
return arr.length - 1;
}
int left = 0;
int right = arr.length - 1;
int mid;
while (left + 1 < right) {
mid = (left + right) / 2;
if (target == arr[mid]) {
return mid;
} else if (target > arr[mid]) {
left = mid;
} else {
right = mid;
}
if (target == arr[left]) {
return left;
}
if (target == arr[right]) {
return right;
}
count++;
}
return -1;
}
}
01-04
453
11-27
1万+