编辑代码

public class BinarySearch {
    public static int binarySearch(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2; // 防止(left + right)的和超过int类型的最大值

            if (array[mid] == target) {
                return mid; // 找到目标值,返回其索引
            } else if (array[mid] < target) {
                left = mid + 1; // 如果目标值大于中间值,搜索右半部分
            } else {
                right = mid - 1; // 如果目标值小于中间值,搜索左半部分
            }
        }

        return -1; // 没有找到目标值,返回-1
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 7;
        int result = binarySearch(array, target);
        System.out.println(result != -1 ? "Element found at index: " + result : "Element not found");
    }
}