二分查找必须要根据一个有序数组进行查找,数组的排序规则可以是正序或者倒序
public class BinarySearch {
public static void main(String[] args) {
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} ;
int index = binarySearch(arr, 7);
System.out.println(index);
int arrDesc[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0} ;
int indexDesc = binarySearch(arrDesc, 7);
System.out.println(indexDesc);
}
public static int binarySearch(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return -1;
}
if (arr[0] == target) {
return 0;
}
if (arr[arr.length - 1] == target) {
return arr.length - 1;
}
if (arr.length == 1) {
return -1;
}
boolean asc = true;
if (arr[0] > arr[arr.length - 1]) {
asc = false;
}
return binarySearch(arr, target, asc);
}
}
取得数组中间的值,遍历数组,跳出循环的条件是低位下标大于高位下标,即数组遍历完毕,判断中间下标的值与目标之间的大小,相等的话就直接返回结果,大于的话就需要判断数组是正序还是倒序,正序的话说明目标数在数组左侧,所以设置高位下标,然后重新遍历一次计算中间值,否则就在数组右侧查找,设置低位下标,反之亦然。
public static int binarySearch(int[] arr, int target, boolean asc) {
int low = 0, high = arr.length - 1, mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
if (asc) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
if (asc) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}