二分查找法

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int i = binarySearch(arr, 6);
        System.out.println("i = " + i);//i = 5
    }

    public static int binarySearch(int[] arr, int key) {
        //定义变量,保存数组最小索引
        int min = 0;
        //定义变量,保存数组最大索引
        int max = arr.length - 1;
        //定义变量,保存数组折半后的中间索引
        int mid = 0;
        //循环折半  最小索引<=最大索引  时,才能折半
        while (min <= max) {
            //折半
            mid = (min + max) / 2;
            //中间索引上的元素和关键字比较
            if (arr[mid] < key) {
                //最小索引=中间索引+1
                min = mid + 1;
            }
            //中间索引上的元素和关键字比较
            else if (arr[mid] > key) {
                //最大索引=中间索引-1
                max = mid - 1;
            }
            //中间索引上的元素和关键字相等,即找到了
            else {
                //返回索引
                return mid;
            }
        }
        return -1;
    }

 

public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int i = binarySearch(arr, 6);
System.out.println("i = " + i);//i = 5
}

public static int binarySearch(int[] arr, int key) {
//定义变量,保存数组最小索引
int min = 0;
//定义变量,保存数组最大索引
int max = arr.length - 1;
//定义变量,保存数组折半后的中间索引
int mid = 0;
//循环折半 最小索引<=最大索引 时,才能折半
while (min <= max) {
//折半
mid = (min + max) / 2;
//中间索引上的元素和关键字比较
if (arr[mid] < key) {
//最小索引=中间索引+1
min = mid + 1;
}
//中间索引上的元素和关键字比较
else if (arr[mid] > key) {
//最大索引=中间索引-1
max = mid - 1;
}
//中间索引上的元素和关键字相等,即找到了
else {
//返回索引
return mid;
}
}
return -1;
}
posted @ 2020-10-13 23:24  SimonShixinlong  阅读(127)  评论(0)    收藏  举报