时间复杂度为O(logN)的常用算法

时间复杂度为O(logN)的常用算法

折半查找

/*
     * 折半查找
     * 默认查找的数组已经排过序
     */
    public static int binarySearch(int[] a,int x){
        int low=0,high=a.length-1;
        while(low<=high){
            int mid =(low+high)/2;
            if(a[mid]<x){
                low=mid+1;
            }else if(a[mid]>x){
                high=mid-1;
            }else{
                return mid;
            }
        }
        return -1;
    }

欧几里得算法

/*
     * 欧几里得算法求最大公因数
     * 默认m>n
     */
    public static int gcd(int m,int n){
        while(n!=0){
            int rem=m%n;
            m=n;
            n=rem;
        }
        return m;
    }

幂运算

/*
     * 幂运算
     */
    public static int pow(int x,int n){
        if(n==0)
            return 1;
        if(n==1)
            return x;
        if(n%2==0)
            return pow(x*x,n/2);
        else
            return pow(x*x,n/2)*x;
    }
原文地址:https://www.cnblogs.com/xtuxiongda/p/8777168.html