二分查找算法是一种高效的查找算法,适用于已排序
的数组或列表。该算法通过不断将待查找区间缩小一半
的方式来快速定位目标元素的位置。
二分查找算法的使用场景包括在大量数据中快速查找目标元素,例如在有序数组中查找特定元素。
一、递归方式实现
代码如下:
public class BinarySearchRecursive {
public static int binarySearch(int[] arr, int target, int left, int right) {
if (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearch(arr, target, mid + 1, right);
} else {
return binarySearch(arr, target, left, mid - 1);
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
int result = binarySearch(arr, target, 0, arr.length - 1);
if (result != -1) {
System.out.println("index: " + result);
} else {
System.out.println("not found");
}
}
}
二、非递归实现
代码如下:
public class BinarySearchIterative {
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;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("index: " + result);
} else {
System.out.println("not found");
}
}
}