欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找算法及时间复杂度

程序员文章站 2024-03-20 10:07:52
...
public class Test{
    public static void main(String[] args){
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        System.out.println(binarySearch(arr, 11));
    }
    private static int binarySearch(int[] arr, int key){
        int low = 0;
        int high = arr.length-1;
        int middle;
        while(low <= high){
            middle = (low+high)/2;
            if(arr[middle] > key){
                high = middle-1;
            }else if(arr[middle] < key){
                low = middle+1;
            }else{
                return middle;
            }
        }
        return -1;
    }
}

时间复杂度:O(log2n)