折半查找

#include <iostream>
using namespace std;

int bisearch(int* a,int low,int high,int h)//递归调用
{
    int f = (low + high) / 2;
    if (a[f] == h) return f;
    else if (h < a[f]) bisearch(a, low, f - 1, h);
    else if (h > a[f])bisearch(a, f + 1, high, h);
    else return -1;
}

int bisearch(int* a, int high, int h)//非递归调用
{
    int low=0, f;
    while (low <= high)
    {
        f = (low + high) / 2;
        if (a[f] == h) return f;
        else if (h < a[f]) high = f - 1;
        else low = f + 1;
    }
    return -1;
}

int main()
{
    int n, h=1 , i = 0;
    int* a;
    cout << "请输入数据个数:";
    cin >> n;
    a = new int[n];
    cout << "请按数据从小到大的顺序依次输入各数据:" ;
    while (i!=n)
    {
        cin >> a[i];
        i++;
    }
    while (h != 0)
    {
        cout << "\n请输入需要查找的数据(输入0退出):";
        cin >> h;
        int f = bisearch(a, n - 1, h);
        if (f == -1 && h != 0)
            cout << "该数据不存在!" << endl;
        else if (h != 0)
            cout << "该数据已找到! \n数据—》位置为:" << a[f] << "->" << f + 1 << endl;
    }
    return 0;
}

  

上一篇:数据结构排序之插入排序(二)


下一篇:TP6管理后台实战第四天-权限管理