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("元素的索引为: " + result);
} else {
System.out.println("数组中找不到此元素。");
}
}
}