编辑代码

public class BinarySearch {
    public static int BinarySearch(int[] arr, int target) {
        //定义首尾
        int left = 0;
        int right = arr.length - 1;

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

            if (arr[mid] == target) {
                return mid; // 找到目标元素,返回索引
            } else if (arr[mid] < target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1; //若找不到,返回-1
    }

    public static void main(String[] args) {
        int[] sortedArray = {85, 63, 52, 34, 25, 17, 6};
        int target = 6;
        //调用二分查找子程序获得元素在数组中的索引
        int result = BinarySearch(sortedArray, target);

        if (result != -1) {
            System.out.println("元素的索引为: " + result);
        } else {
            System.out.println("数组中找不到此元素。");
        }
    }
}