算法入门—二分法查找

O(logn)

    /**
     * 二分法查找
     * @param list 有序数组
     * @param target   查找目标
     * @return 目标位置
     */
    private static int binarySearch(int[] list, int target) {

        int high = list.length - 1;
        int low = 0;

        int mid;

        do {
            //求中间数
            mid = (high + low) / 2;

            int guess = list[mid];
            if (guess == target) {
                //找到了
                return mid;
            } else if (guess > target) {
                //猜的数字大了
                high = mid - 1;
            } else {
                //猜的数字小了
                low = mid + 1;
            }

        } while (low <= high);


        return -1;
    }