编辑代码

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 + " 不存在于数组中。");
        }
    }
}