编辑代码

public class BinarySearch {  
    public static int binarySearch(int[] arr, int left, int right, int x) {  
        while (left <= right) {  
            int mid = left + (right - left) / 2;  
            if (arr[mid] == x) {  
                return mid;  
            }  
            if (arr[mid] > x) {  
                left = mid + 1;  
            } else {  
                right = mid - 1; 
            }  
        }  
        // 如果 x 不在数组中,返回-1  
        return -1;  
    }  
      
    public static void main(String[] args) {  
        // 定义有序数组  
        int[] arr = {85, 63, 52, 34, 25, 17, 6};  
        // 计算数组长度  
        int n = arr.length;  
        // 要查找的元素  
        int x = 6;  
        // 调用二分查找函数  
        int result = binarySearch(arr, 0, n - 1, x);  
        if (result == -1) {  
            System.out.println("元素 " + x + " 不在数组中");  
        } else {  
            System.out.println("元素 " + x + " 在数组中的索引为 " + result);  
        }  
    }  
}