二分查找法

要求给定数据是有序的:

int BinarySearch1(vector<int> num, int n)
{
    int left = 0, right = num.size() - 1;
    int mid ;
    while (left<= right)
    {
        mid = left + (right - left) / 2;
        if (num[mid] > n)
            right = mid - 1;
        else if (num[mid] < n)
            left = mid + 1;
        else
            return mid;
    }    
    return -1;
}

时间复杂度O(logn)

posted @ 2018-03-20 22:06  东风知我欲山行  阅读(100)  评论(0编辑  收藏  举报