插值查找法

需要注意的是算between的时候应该先算乘法后算除法 

/*
插值查找法:适用于分布均匀的数据中查找,也得是从小到大分布均匀,比如说成绩喽。
是按照数据位置的分布并利用公式Between = low + (key - data[low])/(data[high] - data[low]) * (high - low)
预测数据的所在位置。
*/

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

void InSearch(int *data, int nFound);                //在数组data中找到nFound

void main()
{
	//建立数据库
	srand((unsigned)time(NULL));
	cout << "数据为:\n";
	int nData[100];
	int i;
	nData[0] = rand()%5;
	cout << "1->" << nData[0] << "\t";
	for(i = 1; i < 100; i++)
	{
		nData[i] = (nData[i-1]+rand()%5+1);
		cout << i+1 << "->" << nData[i] << "\t";
	}
	cout << endl;

	//查找
    cout << "请输入要查找的数字:";
	cin >> i;
	InSearch(nData,i);
}


void InSearch(int *data, int nFound)                 //在数组data中找到nFound
{
	int nlow = 0, nhigh = 99;
	int nBetween;
	int nBJ = 0;                                     //设置标记位
	while(nlow < nhigh && nBJ == 0)
	{
      nBetween = nlow + (nFound - data[nlow])* (nhigh - nlow) / (data[nhigh] - data[nlow]);
	  if(data[nBetween] == nFound)
	  {
		  nBJ = 1;
	  }
	  else if(data[nBetween] > nFound)
		  nlow = nBetween;
	  else
		  nhigh = nBetween;
	}

	if(nBJ == 0)
		cout << "没有找到这个数据!\n";
	else
		 cout << nBetween+1 << "->" << nFound;
	cout << endl;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值