斐波那契查找(数据结构)

殷人昆《数据结构》第二版的7.25题

#include 
#include 
#include 
using namespace std;

#define MOD 50
#define SIZE 13

int fib_search(int x, int n, int fib[], int ar[])
{
    int k = 2, l = 1, r = n, mid, offset = 0;

    while (fib[k] - 1 < n) k++;
    while (l <= r)
    {
        mid = offset + fib[k - 1];
        if (ar[mid] == x) return mid;
        else if (ar[mid] > x) k--;
        else {
            k -= 2;
            offset = mid;
        }
        r = fib[k] - 1;
    }
    return -1;
}

int main()
{
    int fib[SIZE] = { 0, 1 }, ar[13], i, x;

    srand(time(0));
    cout << "程序已随机生成n = 12的顺序表。" << endl;
    //cout << "fib: " << fib[0] << " " << fib[1] << " ";
    for (i = 2; i < SIZE; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
        //cout << fib[i] << " ";
    }
    //cout << endl;
    cout << "ar : ";
    for (ar[0] = 0, i = 1; i < SIZE; i++) {
        ar[i] = ar[i - 1] + rand() % MOD;
        cout << ar[i] << " ";
    }
    while (true) {
        cout << "\n请输入被查找数(-1退出):"  << endl;
        cin >> x;
        if (x == -1) break;
        cout << fib_search(x, SIZE - 1, fib, ar) << endl;
    }
    return 0;
}


你可能感兴趣的:(数据结构,数据结构,search)