Java算法-二分查找

二分查找前提条件:数组有序

public class BinarySearch {
    public static void main(String[] args) {
        int[] data = {0, 1, 2, 3, 4, 5};
        int num = 5;
        // 5
        System.out.println(binarySearch(data, num));
        // 1
        System.out.println(binarySearch(data, 1));
        // -1
        System.out.println(binarySearch(data, 7));
    }

    /**
     * 二分查找
     *
     * @param data the data
     * @param num  the num
     * @return the int
     */
    private static int binarySearch(int[] data, int num) {
        if (data == null || data.length == 0) {
            return -1;
        }
        int mid;
        int left = 0;
        int right = data.length - 1;
        while (left <= right) {
            // 避免加法溢出
            mid = left + ((right - left) >> 1);
            if (data[mid] < num) {
                // 中间值小于num,说明num在右边,故去右边查找
                left = mid + 1;
            } else if (data[mid] > num) {
                // 中间值大于num,说明num在左边,故去左边查找
                right = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}

你可能感兴趣的:(Java,算法,二分法,java)