/**************************************************
斐波那契查找
low=1;high=F(k)-1=n; // 设置初始区间
M=F(k)-1;f=F(k-1)-1; // M 为表长,f 为取中点的相对偏移量
当low>high 时,返回查找失败信息// 表空,查找失败
low≤high,mid=low+f; // 取中点
a. 若kx<tbl.elem[mid].key,则
p=f;f=M-f-1; // 计算取中点的相对偏移量
M=p; // 调整表长F
high=mid-1;转② // 查找在左半区进行
b. 若kx>tbl.elem[mid].key,则
M=M-f-1; // 调整表长M
f=f-M-1; // 计算取中点的相对偏移量
low=mid+1;转② // 查找在右半区进行
c. 若kx=tbl.elem[mid].key,返回数据元素在表中位置// 查找成功
***************************************************/
//符合限制条件,n为斐波那契数-1
#include <stdio.h>
void feibonaqie(int *f) //产生斐波那契数列
{
int i;
f[0] = 1;
f[1] = 1;
for(i = 2; i < 10; i++)
{
f[i] = f[i-1] + f[i-2];
}
}
int feibonaqiechazhao(int *a, int n, int key) //斐波那契额查找
{
int low = 1;
int high = n;
int i,f,M,p,k = 0;
int mid, F[10];
feibonaqie(F);
for(i = 0; i < 10; i++)
{
printf("%d ",F[i]);
}
printf("\n");
while(n > F[k] - 1)
{
k++;
}
if(low > high)
{
return -1;
}
f = F[k-1] - 1; //4
M = F[k] - 1; //7
while(low <= high)
{
mid = low + f;
if(key == a[mid])
{
return mid;
}
if(key < a[mid])
{
p = f;
f = M - f -1;
M = p;
high = mid -1;
}
if(key > a[mid])
{
M = M - f - 1;
f = f - M - 1;
low = mid + 1;
}
}
return -1;
}
int main()
{
int i,flag;
int array[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
for(i = 0; i < 12; i++)
{
printf("%d ",array[i]);
}
printf("\n");
flag = feibonaqiechazhao(array, 12, 11);
if(flag != -1)
{
printf("The find is successful!\n");
printf("The number is array[%d]\n",flag);
}
else
{
printf("The find is wrong!\n");
}
return 0;
}