public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 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 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
30};
int target = 18;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("
⽬
标
值
不
存
在
");
} else {
System.out.println("
⽬
标
值
在
数
组
中
的
索
引
为
: " + result);
}
}
}