# Fibonacci 搜索法

```#include <stdio.h>
void fibonacci(int *f)
{
f[0] = 1;
f[1] = 1;
for(int i = 2;i < MAXSIZE;++i)
f[i] = f[i - 2] + f[i - 1];
}
int fibonacci_search(int *a,int key,int n)
{
int low = 0,high = n - 1;
int mid = 0;
int k = 0;
int F[MAXSIZE];
fibonacci(F);
while(n > F[k] - 1) //计算出n在斐波那契中的数列
++k;
for(int i = n;i < F[k] - 1;++i) //把数组补全
a[i] = a[high];
while(low <= high)
{
mid = low + F[k-1] - 1;  //根据斐波那契数列进行黄金分割
if(a[mid] > key)
{
high = mid - 1;
k = k - 1;
}
else if(a[mid] < key)
{
low = mid + 1;
k = k - 2;
}
else{
if(mid <= high) //如果为真则找到相应的位置
return mid;
else
return -1;
}
}
return -1;
}
int main()
{

int a[MAXSIZE] = {5,15,19,20,25,31,38,41,45,49,52,55,57};
int k;
printf("请输入要查找的数字:\\n");
scanf("%d",&k);
int pos = fibonacci_search(a,k,13);
if(pos != -1)
printf("在数组的第%d个位置找到元素:%d\\n",pos + 1,k);
else
printf("未在数组中找到元素:%d\\n",k);
return 0;
}
//该片段来自于http://outofmemory.cn
```

0人收藏

0

0

»更多 您可能感兴趣的代码
1. 2013-07-25 21:20:53二叉树深度优先遍历说明和c++的实现 by 玉开Sir
2. 2014-02-05 13:32:07C++算法之图的结构 by walker30
3. 2014-02-16 18:20:02C++解决八皇后问题 by aiheng1988
4. 2014-03-05 16:11:07C++挑选一组数中最大的N个数 by niutao.linux
5. 2014-05-13 19:31:43排序算法 by 蟋蟀哥
6. 2014-05-14 18:05:23递归方法实现全排列 by 童学芬
7. 2014-05-22 12:36:50单链表的各种操作 by 千万不要郁闷
8. 2014-05-28 14:39:00C++算法之线性队列 by 小项
9. 2014-06-30 20:50:04线性表 by lucasli
10. 2014-07-10 10:49:57快速排序 [C遮言泛型版] by sxgkwei
11. 2014-08-08 12:12:47sudoku求解数独 by aiheng1988