C++二分检索算法

余祥宣, 崔国华, 邹海明. 计算机算法基础.3版[M]. 华中科技大学出版社, 2006.
P73 算法4.3

#include
using namespace std;

int BINSRCH(int A[], int n, int x, int &j)
{
    int low, high, mid;
    low = 1;
    high = n;
    while (low <= high)
    {
        mid = (low + high) / 2;
        if (x < A[mid])
            high = mid - 1;
        else if (x > A[mid])
            low = mid + 1;
        else
        {
            j = mid;
            return j;
        }
    }
    j = 0;
    return j;
}

int main()
{
    int a[10] = { 0,-15,-6,0,7,9,23,54,82,101 };
    int n = 9;
    int x = 101;
    int j = 0;
    for (int i = 1; i <= 9; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;
    cout << "BINSRCH(a," << n << "," << x << ",j)=" << BINSRCH(a, n, x, j);
    cout << " a[" << j << "]=" << a[j] << endl;

    x = -14;
    cout << "BINSRCH(a," << n << "," << x << ",j)=" << BINSRCH(a, n, x, j);
    cout << " a[" << j << "]=" << a[j] << endl;

    x = 82;
    cout << "BINSRCH(a," << n << "," << x << ",j)=" << BINSRCH(a, n, x, j);
    cout << " a[" << j << "]=" << a[j] << endl;

    system("pause");
    return 0;
}

运行结果
C++二分检索算法_第1张图片

你可能感兴趣的:(算法,算法)