您的位置:首页 > 其它

第14周项目1-(1)验证折半查找算法

2015-12-14 16:47 399 查看
/*
* Copyright (c)2015,烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:项目1-1.cbp
* 作者:李涵睿
* 完成日期:2015年12月14日
* 版 本 号:v1.0
* 问题描述:验证折半查找算法

* 输入描述:无
* 程序输出:测试数据
*/

非递归方式:

#include <iostream>
using namespace std;
int main()
{
int low=0,high,n;
int a[100];
int i=0,f;
cout<<"Please input the number of data and what data do you want to find"<<endl;
while(cin>>n)
{

cin>>f;
high=n-1;
while(i<n)
{
cin>>a[i];
i++;
}
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==f)
{
cout<<"find in the postion "<<mid+1<<endl;
break;
}
if(a[mid]>f)
{
high=mid-1;
}
else
{
low=mid+1;
}

}
if(low>high)
{
cout<<"can't find it"<<endl;
}
cout<<"Please input the number of data and what data do you want to find"<<endl;
low=0;
i=0;
}
return 0;

}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: