二分查找

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
        int num = 70;

        System.out.println(binarySearchMethods(num, arr));
    }

    /**
     * arr必须为排序后的数组
     */
    public static int binarySearchMethods(int num, int[] arr) {
        int minindex = 0;
        int maxindex = arr.length;
        while (true) {
            if (minindex == maxindex) {
                return (minindex + maxindex) / 2;
            } else {
                if (num < arr[(minindex + maxindex) / 2]) {
                    maxindex = (minindex + maxindex) / 2 - 1;
                } else if (arr[(minindex + maxindex) / 2] < num) {
                    minindex = (minindex + maxindex) / 2 + 1;
                } else {
                    return (minindex + maxindex) / 2;
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/linding/p/13489888.html