BinarySearch

Type:  logarithmic algorithm

Performance: O(log N)

Worse case: logN + 1

Requirement - a is already sorted

return index of the key from the array or -1 if not found

    public static int binarySearch( int[] a, int key ){
        int lo = 0, hi = a.length - 1;
        while( lo <= hi ){
            int mid = lo + (hi - lo)/2;
            if (a[mid]>key) hi = mid-1;
            else if(a[mid]<key) lo = mid+1;
            else return mid;
        }
        return -1;
    }



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