思想
二分查找是一种在有序数组中查找特定元素位置的高效算法。它通过不断将查找范围减半,从而快速锁定目标元素的位置。其基本思想是:
- 确定中间点:在当前查找范围内,找出中间点。
- 比较中间点值:将中间点的值与目标值进行比较。
- 如果相等,则找到目标值,返回中间点的位置。
- 如果中间点值大于目标值,则目标值只可能出现在中间点左侧,将查找范围缩小至左半部分。
- 如果中间点值小于目标值,则目标值只可能出现在中间点右侧,将查找范围缩小至右半部分。
- 重复上述步骤:不断缩小查找范围,直到找到目标值或者查找范围为空。
使用场景
二分查找适用于以下场景:
- 查找有序数组中的元素。
- 在搜索引擎中,查找排序后的关键词。
- 数据库索引查找。
- 查找满足特定条件的最小/最大值(如数值计算中的根号问题)。
代码示例
闭区间[left,right]
public class BinarySearch {
// 二分查找方法,返回目标值在数组中的索引,如果找不到则返回-1
public static int binarySearch(int[] arr, int target) {
int left = 0; // 左边界
int right = arr.length - 1; // 右边界
while (left <= right) {
int mid = left + (right - left) / 2; // 计算中间点,避免直接相加可能导致的溢出
if (arr[mid] == target) {
return mid; // 找到目标值,返回索引
} else if (arr[mid] < target) {
left = mid + 1; // 目标值在右半部分,调整左边界
} else {
right = mid - 1; // 目标值在左半部分,调整右边界
}
}
return -1; // 未找到目标值,返回-1
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 有序数组
int target = 5; // 目标值
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("元素 " + target + " 位于数组的索引 " + result);
} else {
System.out.println("元素 " + target + " 不在数组中");
}
}
}
左闭右开 [left,right)
public class BinarySearch {
// 二分查找方法,返回目标值在数组中的索引,如果找不到则返回-1
public static int binarySearch(int[] arr, int target) {
int left = 0; // 左边界
int right = arr.length; // 右边界,注意这里是开区间,右边界为数组长度
while (left < right) { // 开区间[left, right)
int mid = left + (right - left) / 2; // 计算中间点,避免直接相加可能导致的溢出
if (arr[mid] == target) {
return mid; // 找到目标值,返回索引
} else if (arr[mid] < target) {
left = mid + 1; // 目标值在右半部分,调整左边界
} else {
right = mid; // 目标值在左半部分,调整右边界
}
}
return -1; // 未找到目标值,返回-1
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 有序数组
int target = 5; // 目标值
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("元素 " + target + " 位于数组的索引 " + result);
} else {
System.out.println("元素 " + target + " 不在数组中");
}
}
}
左开右开(left,right)
public class BinarySearch {
// 二分查找方法,返回目标值在数组中的索引,如果找不到则返回-1
public static int binarySearch(int[] arr, int target) {
int left = -1; // 左边界,注意这里是左开区间,初始值设为-1
int right = arr.length; // 右边界,右开区间
while (left + 1 < right) { // 保持(left, right)为开区间
int mid = left + (right - left) / 2; // 计算中间点,避免直接相加可能导致的溢出
if (arr[mid] == target) {
return mid; // 找到目标值,返回索引
} else if (arr[mid] < target) {
left = mid; // 目标值在右半部分,调整左边界
} else {
right = mid; // 目标值在左半部分,调整右边界
}
}
return -1; // 未找到目标值,返回-1
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 有序数组
int target = 5; // 目标值
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("元素 " + target + " 位于数组的索引 " + result);
} else {
System.out.println("元素 " + target + " 不在数组中");
}
}
}
复杂度分析
时间复杂度
二分查找的时间复杂度为 O(logn)O(\log n)O(logn),其中 nnn 是数组的长度。每次查找都将查找范围减半,因此时间复杂度是对数级的。
空间复杂度
二分查找的空间复杂度为 O(1)O(1)O(1),因为它只使用了常量级别的额外空间(几个指针变量),并不需要额外的数组或其他数据结构。