int F[] = {0,1,1,2,3,5,8,13,21,34};
int research2(int*a, int n, int key) {
int low = 0,high = n - 1,mid;
int k = 0;
while (n-1 > F[k]-1)
k++;
for (int i = n; i < F[k]-1; i++)
a[i] = a[n-1];//F[k-1]-1可能大于n,所以做一个补全数组的操作,保证mid=low+F[k-1]-1一定是在补全后的数组范围内
while (low <= high) { 补全后的数组长度其实就是F[k]-1 ( F[k]-1=F[k-1]-1 + F[k-2]-1 + 1 )
mid = low + F[k - 1] - 1;
if (key < a[mid]) {
high = mid - 1;
k = k - 1;
}
else if (key>a[mid]) {
low = mid + 1;
k = k - 2;
}
else {
if (mid <n)
return mid;
else
return n-1;
}
}
return -1;
}
斐波那契查找
最新推荐文章于 2024-08-16 08:54:09 发布