public class BinarySearch {
public int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
int[] arr = { 2, 3, 5, 7, 9, 10};
int target = 7;
int result = bs.binarySearch(arr, target);
if (result == -1)
System.out.println("目标元素不存在于该数组中");
else
System.out.println("目标元素在数组中的索引为:" + result);
}
}