一、原理
对于有序的数组,不是顺序的查找,而是折半的查找,对比查找的值与数组中间值,逐步缩短查找范围。
时间复杂度: 最好(直接命中)O(1) 最坏(最边缘命中) O(log2n)
空间复杂度: 常规O(1) 递归O(log2n)
二、举例
arr = {1,2,3,4,5,6,7,8,9,10}
low: 左边界 high: 右边界 mid:(low+high)/2
- 查找5
直接命中 - 查找1
- 查找10
三、 代码实现
public class BinarySearch {
//常规二分查找
public static Boolean binarySearch(int[] arr, int target) {
int length = arr.length - 1;
int low = 0;
int high = length;
boolean result = false;
while (low <= high) {
int mid = (high + low) / 2;
System.out.println("low: " + arr[low] + " mid:" + arr[mid] + " high:" + arr[high] + " target:" + target);
if (arr[mid] > target) {
high = mid - 1;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
result = true;
break;
}
}
return result;
}
//递归二分查找
public static Boolean binarySearchByRecursion(int[] arr, int target, int low, int high) {
if (low <= high) {
int mid = (low + high) / 2;
System.out.println("low: " + arr[low] + " mid:" + arr[mid] + " high:" + arr[high] + " target:" + target);
if (arr[mid] > target) {
return binarySearchByRecursion(arr, target, low, mid - 1);
} else if (arr[mid] < target) {
return binarySearchByRecursion(arr, target, mid + 1, high);
} else {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println(binarySearch(arr, 10));
// System.out.println(binarySearchByRecursion(arr, 1, 0, arr.length - 1));
}
}
四、优缺点
优点: 比顺序查找节约时间
缺点: 数组必须有序