编辑代码

public class BinarySearchExample {

    // 二分查找算法
    public static boolean binarySearch(int[] arr, int key) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == key) {
                return true; // 找到了元素
            } else if (arr[mid] < key) {
                left = mid + 1; // 在右侧继续查找
            } else {
                right = mid - 1; // 在左侧继续查找
            }
        }

        return false; // 没有找到元素
    }

    public static void main(String[] args) {
        int[] sortedArray = {6, 17, 25, 34, 52, 63, 85};
        int searchElement = 6;

        boolean isElementPresent = binarySearch(sortedArray, searchElement);

        if (isElementPresent) {
            System.out.println("元素 " + searchElement + " 存在于数组中。");
        } else {
            System.out.println("元素 " + searchElement + " 不存在于数组中。");
        }
    }
}