递归实现:
public static int binarySearchRecursive(int[] arr, int target) {
return binarySearchRecursive(arr, target, 0, arr.length - 1);
}
private static int binarySearchRecursive(int[] arr, int target, int low, int high) {
if (low > high) {
return -1; // 没有找到目标元素
}
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid; // 找到目标元素,返回索引
} else if (target < arr[mid]) {
return binarySearchRecursive(arr, target, low, mid - 1); // 在左半部分继续查找
} else {
return binarySearchRecursive(arr, target, mid + 1, high); // 在右半部分继续查找
}
}
迭代实现:
public static int binarySearchIterative(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid; // 找到目标元素,返回索引
} else if (target < arr[mid]) {
high = mid - 1; // 在左半部分查找
} else {
low = mid + 1; // 在右半部分查找
}
}
return -1; // 没有找到目标元素
}