编程语言
首页 > 编程语言> > [算法]二分搜素

[算法]二分搜素

作者:互联网

算法复杂度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;
}

标签:二分,10,right,int,mid,算法,搜素,left
来源: https://www.cnblogs.com/tailiang/p/11730475.html