1、二分查找法

二分查找算法
1.二分查找又称折半查找,它是一种效率较高的查找方法。
2.二分查找要求:(1)必须采用顺序存储结构 (2)必须按关键字大小有序排列
3.原理:将数组分为三部分,依次是前值,中值,后值;将要查找的值和数组的中值进行比较,若小于中值则在中值前 面找,若大于中值则在中值后面找,等于中值时直接返回。然后依次是一个递归过程,将前半部分或者后半部分继续分解为三部分。
4.实现:二分查找的实现用递归和循环两种方式:

public class BinarySearch {
    /**
     * 递归实现二分查找
     * @param dataset 有序数组
     * @param target  需要找出target值的下标
     */
    public static int binarySearch(int[] dataset, int target, int beginIndex, int endIndex) {
        if (target < dataset[beginIndex] || target > dataset[endIndex] || beginIndex > endIndex) {
            return -1;
        }

        int midIndex = (beginIndex + endIndex) / 2;

        if (target < dataset[midIndex]) {
            return binarySearch(dataset, target, beginIndex, midIndex - 1);
        } else if (target > dataset[midIndex]) {
            return binarySearch(dataset, target, midIndex + 1, endIndex);
        } else {
            return midIndex;
        }
    }

    /**
     * 循环实现二分查找算法
     * @param dataset 有序数组
     * @param target  需要找出target值的下标
     */
    public static int binarySearch(int[] dataset, int target) {
        int low = 0;
        int high = dataset.length - 1;

        while (low <= high) {
            int middle = (low + high) / 2;
            if (target == dataset[middle]) {
                return middle;
            } else if (target < dataset[middle]) {
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {6, 12, 33, 87, 90, 97, 108, 561};

        System.out.println("递归查找:" + binarySearch(arr, 87, 0, arr.length - 1));
        System.out.println("循环查找:" + (binarySearch(arr, 87)));
    }
}

不管使用那种方式,时间复杂度为 log2n

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章