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 - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] sortedArray = {85, 63, 52, 34, 25, 17, 6};
int target = 6;
int result = BinarySearch(sortedArray, target);
if (result != -1) {
System.out.println("元素 " + target + " 在数组中的索引是 " + result);
} else {
System.out.println("元素 " + target + " 不在数组中");
}
}
}