二分查找--c++

/*算法描述:来自《算法分析与设计》 代码来自网络QAQ*/
/*
* 输入:n个元素的升序数组A[1,...,n]和元素x
* 输出:如果x = A[j], 1<=j<=n,则输出j, 否则输出0
* low <- 1; high <- n; j <- 0
* while (low<=high) and (j=0)
*     mid <- (low+high)/2
*     if x = A[mid] then j <- mid
*     else if x < A[mid] then high <- mid-1
*     else low <- mid+1
* end while
* return j
*/
//非递归
int BinarySearch(int *A, int aSize, int key)
{
    if ( A == NULL || aSize == 0)
        return -1;
    int low = 0;
    int high = aSize - 1;
    int mid = 0;

    while (low <= high)
    {
        mid = (low + high)/2;
        if (A[mid] < key)
            low = mid + 1;
        else if (A[mid] > key)
            high = mid - 1;
        else
            return mid;
    }
    return -1;
}

//递归
int BinarySearchRecursive(int *A, int low, int high, int key)
{
    if (low > high)
        return -1;
    int mid = (low + high)/2;
    if (A[mid] == key)
        return mid;
    else if (A[mid] < key)
        return BinarySearchRecursive(A, mid+1, high, key);
    else
    {
        return BinarySearchRecursive(A, low, mid-1, key);
    }
    
}

int main()
{
    int A[10];
    for (int i=0; i<10; i++)
        A[i] = i;
    cout << "No recursive:" << endl;
    cout << "position:"<< BinarySearch(A, 10, 6) << endl;
    cout << "recursive:" << endl;
    cout << "position:" << BinarySearchRecursive(A, 0, 9, 6) << endl;

    return 0;
posted @ 2020-04-07 23:02  ho_ho  阅读(185)  评论(0编辑  收藏  举报