二分查找之斐波那契查找

1、什么是Fibonacci数列?

      斐波那契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、····,在数学上,斐波那契被递归方法如下定义:F(1)=1,F(2)=1,F(n)=f(n-1)+F(n-2) (n>=2)。该数列越往后相邻的两个数的比值越趋向于黄金比例值(0.618)

2、什么是Fibonacci查找?

     Fibonacci查找就是在二分查找的基础上根据斐波那契数列进行分割的。在斐波那契数列找一个等于略大于查找表中元素个数的数F[n],将原查找表扩展为长度为F[n](如果要补充元素,则补充重复最后一个元素,直到满足F[n]个元素:参见注释2处代码),完成后进行斐波那契分割,即F[n]个元素分割为前半部分F[n-1]个元素,后半部分F[n-2]个元素,找出要查找的元素在那一部分并递归,直到找到。

3、为什么使用Fibonacci查找?

      斐波那契的时间复杂度也为O(log n),相对与折半查找(mid=(low + high)/2)和差值查找(mid=low+(key-a[low])/(a[high]-a[low])*(high-low))进行加法与除法运算,斐波那契查找只是最简单加减法运算(mid = low + F(k-1) -1),在海量数据的查找过程中,这种细微的差别可能会影响最终的查找效率

4、Fibonacci查找代码实现(C++):

#include <stdio.h>
#include <iostream>
using namespace std;
#define MAXSIZE 20
void fibonacci_1(int *f)  //fibonacci数列实现方法1
{
	f[0] = 0;
	f[1] = 1;
	for (int i = 2 ; i<MAXSIZE ; i++)
	{
		f[i] = f[i - 1] + f[i - 2];
	}
}
int fibonacci_2(int n)   //fibonacci数列实现方法2
{
	int result,previous_result,temp;
	result = previous_result = 1;
	while(n>2)
	{
		temp=result;
		result+=previous_result;
		previous_result=result;
		n--;
	}
	return result;
}
int Fibonacci_Search(int *a, int n, int key)
{
	int low, high, mid, k;
	int F[MAXSIZE];
	fibonacci_1(F);

    low = 0;
	high = n - 1;
	k = 0;
	while(n > F[k] - 1)  //注释1
		k++;

	for (int i = n ; i <= F[k] - 1 ; i++)  //注释2
	{
		a[i] = a[high];
	}

    while (low <= high)
    {
		mid = low + F[k - 1] - 1;
		if (key < a[mid])
		{
			high = mid - 1;
			k = k - 1;           //注释3
		}
		else if (key > a[mid])
		{
			low = mid + 1;
			k = k - 2;           //注释4
		}
		else
		{
			cout << "Search Success!" << endl;
			if (mid < n)
				return mid;
			else
				return n - 1;
		}
    }
    if (low > high)
	{
		cout << "Search Failed!" << endl;
		return -1;
	}	
	return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
	int n, key;
	cout << "Please input n:" <<endl;
	cin >> n;
	int list[MAXSIZE];
	cout << "Please input your sorted array:" << endl;
	for(int i = 0 ; i < n ;i++)
	{  
		cin >> list[i]; 
	}
	cout << "Please input the key:" << endl;
	cin >> key;
        int pos = Fibonacci_Search(list, n, key);
	cout << "pos = " << pos <<endl;

	system("pause");
	return 0;
}
注释1:通过比较,找到不小于n的斐波那契数的位置

注释2:在斐波那契数列找一个等于略大于查找表中元素个数的数F[n],将原查找表扩展为长度为F[n](下标范围为0~F[n] - 1)

注释3:我们知道,表长为F[n]的查找表在Fibonacci查找中被分为了表长为F[n - 1]和F[n - 2]两部分。因此,当key < list[mid] 的时候,就是k = k - 1
注释4:对于斐波那契查找,分割是从mid =low + F[k - 1] -1 开始的,现在数组的长度为F[k],mid 将数组分为两个部分,前一部分为[0,mid],长度为F[k - 1],则后一部分的长度为F[k] - F[k - 1],根据斐波那契数列的性质,F[k] - F[k - 1] = F[k - 2],则后一部分的长度为F[k - 2],所以当key > list[mid] 的时候 k = k - 2


  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值