[算法]二分搜索

算法复杂度O(logn)
前提,序列要排好序

//成功返回下标,没找到返回-1
int binarySearch(int A[], int x, int n)
{
    int left = 0;
    int right = n - 1;
    while (left<=right)
    {
        int mid = (left + right) / 2;
        if (x == A[mid])
            return mid;
        if (x>A[mid])
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }
    return -1;
}
int main()
{
    int A[10] = { 1,2,3,4,5,6,7,8,9,10 };
    cout << binarySearch(A, 3, 10) << endl;
    return 0;
}

你可能感兴趣的:([算法]二分搜索)