编辑代码

public class BinarySearch {
    // 二分查找算法
    public static boolean binarySearch(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;

        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] == target) {
                return true;  // 元素找到
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return false;  // 元素未找到
    }

    // 主函数测试
    public static void main(String[] args) {
        // 有序数组
        int[] myArray = {6, 17, 25, 34, 52, 63, 85};

        // 要查找的元素
        int targetElement = 6;

        // 调用二分查找算法
        boolean result = binarySearch(myArray, targetElement);

        // 输出结果
        if (result) {
            System.out.println("元素 " + targetElement + " 存在于数组中。");
        } else {
            System.out.println("元素 " + targetElement + " 不存在于数组中。");
        }
    }
}