public class BinarySearch {
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid; // 找到目标元素,返回索引
} else if (array[mid] < target) {
left = mid + 1; // 目标元素在右侧,缩小搜索范围
} else {
right = mid - 1; // 目标元素在左侧,缩小搜索范围
}
}
return -1; // 没有找到目标元素,返回 -1
}
public static void main(String[] args) {
int[] array = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int target = 23;
int result = binarySearch(array, target);
if (result != -1) {
System.out.println("目标元素 " + target + " 的索引为 " + result);
} else {
System.out.println("目标元素 " + target + " 不存在于数组中");
}
}
}