public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
//要求:使用折半查找必须有序且是自然序
int target = 13;
int index = binarySearch(arr, target);
System.out.println(index == -1 ? "Element not found" : "Element found at index " + index);
}
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;
}
}