折半查找

给定一个整数X和整数A0,A1,…,A(N-1),后者已经预先排序并在内存中,求下标i使得Ai=X,如果X不再数据中,则返回i=-1。

package com.ql;

/**
 * @author Administrator
 *binary search
 */
public class BinarySearch {

    private static final int NOT_FOUND = -1;
    public static super AnyType>>
    void main(String[] args){
        Integer [] str = {1,2,3,4,5,6,7};
        System.out.println(binarysearch(str,3));
    }
    /**
     * @author Administrator
     *运行时间O(logN)
     */
    public static super AnyType>>
    int binarysearch(AnyType [] a,AnyType x){
        int low = 0,high = a.length - 1;

        while(low <= high){
            int mid = (low + high)/2;

            if(a[mid].compareTo(x)<0)
                low = mid +1;
            else if (a[mid].compareTo(x)>0)
                high = mid -1;
            else
                return mid;
        }
        return NOT_FOUND;
    }

}

你可能感兴趣的:(数据结构,算法,数据结构与算法,数据结构与算法分析)