public class BinarySearchExample {
static boolean binarySearch(int[] arr, int key) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) {
return true;
} else if (arr[mid] > key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
public static void main(String[] args) {
int[] sortedArray = {85, 63, 52, 34, 25, 17, 6};
int searchKey = 6;
boolean isElementFound = binarySearch(sortedArray, searchKey);
if (isElementFound) {
System.out.println("元素 " + searchKey + " 存在于数组中。");
} else {
System.out.println("元素 " + searchKey + " 不存在于数组中。");
}
}
}