二分搜索

二分搜索:给定一个整数X和整数A0,A1,...,AN-1,后者已经预先排序在内存中,求下标i使得Ai=X,如果X不在数据中,则返回i=-1/**

 * Performs the standard binary search using two coparisons per level.

 * Returns index where item is found or -1 if not found

 */

template

int binarySearch(const vector& a, const Comparable& x)

{

    int low=0, high=a.size()-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;     //Found

    }

    return NOT_FOUND;   //NOT_FOUND is defined as -1

}

 

你可能感兴趣的:(二分搜索)