数据结构 折半查找

#include<iostream>
using namespace std;
#include<stdlib.h>//使用数据库srand和rand 
#include<time.h>//使用库数据time
const int Max=10;//假定带查找集合有10个元素

void Creat(int a[]);
int BinSearch(int r[],int n,int k,int &count);//有序表r[],有序表的数据个数为n,设带查找元素为k,查询次数为count
int main()
{
	int a[Max+1]={0};//假设
	int location=0,count=0,k;
	Creat(a);
	for(int i=1;i<=Max;i++)
	cout<<a[i]<<" ";
	cout<<endl;
	k=a[1+rand()%Max];//随机生成带查找元素的下标 
	location=BinSearch(a,Max,k,count);
	cout<<"元素"<<k<<"在序列中序号是"<<location;
	 cout<<",共比较"<<count<<"次"<<endl;
	 return 0; 
	
} 
void Creat(int a[])//函数定义,随机生成待查找集合 
{
	srand(time(NULL));//初始化随机种子为当前系统随机时间 
	
	a[0]=0;
	for(int i=1;i<=Max;i++)
	a[i]=a[i-1]+rand()%Max;//生成一个递增序列
	 
}
int BinSearch(int r[],int n,int k,int &count)//从数组下标1开始存放待查集合
{
int low=1;
int high=n;//设置查找区间 
int mid;
while(low<=high)//当期间存在时
{
mid=(low+high)/2;
count++;
if(k<r[mid])
high=mid-1;
else if(k>r[mid]) 
low=mid+1;
else return mid;
}
return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值