public class BinarySearch {
public static int binarySearch(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 (arr[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // 目标元素不存在
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int target = 11;
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("目标元素在数组中的索引位置为:" + result);
} else {
System.out.println("目标元素不存在");
}
}
}
Java中二分查找
最新推荐文章于 2024-07-27 17:56:15 发布