查找算法(2)二分查找

一.基本思想

     也称为折半查找,属于有序查找算法,先用给定元素与中间的值进行比较,若不相等,再根据大小查找左边或右边的子表,这样递归查找,直到查找到或查找结束


二.复杂度分析

    最坏情况下,关键词比较次数是log2(n+1),期望时间复杂度为O(log2n)

    折半查找的前提是序列有序,对于静态表(一次排序后不再变化)查找

    但对于频繁插入删除的数据集,维护排序工作量大,不建议使用


三.代码实现

  方式1:

public class Binary {
    public static int search(int a[],int value){
        int N = a.length;
        int low = 0;
        int high = N-1;
        int mid;
        while(low <= high){
            mid = (low+high)/2;
            if (a[mid] == value){
                return mid;
            }
            if(a[mid] > value){
                high = mid -1;
            }
            if (a[mid] < value){
                low = mid +1;
            }

        }
        return -1;
    }

    public static void main(String[] args) {
        int a[] = {1,2,4,5,8};
        System.out.println(search(a, 8));
    }
}

方式2(递归版本):

public class Binary2 {
    public static int search2(int a[],int value,int low,int high){
        int mid = low +(high-low)/2;
        if(a[mid] == value){
            return mid;
        }
        if (a[mid] > value){
            return search2(a, value, low, mid-1);
        }
        if (a[mid] < value){
            return search2(a, value, mid+1, high);
        }
        return -1;
    }

    public static void main(String[] args) {
        int a[] = {1,2,4,5,8};
        System.out.println(search2(a, 8,0,a.length-1));
    }
}


猜你喜欢

转载自blog.csdn.net/qq_34645958/article/details/80742113