第十四周项目1-验证折半查找

来源:互联网 发布:javascript怎么发音 编辑:程序博客网 时间:2024/05/21 07:11
<strong><span style="font-family:KaiTi_GB2312;font-size:32px;color:#ff0000;BACKGROUND-COLOR: #ff0000"><span style="color:#ffffff;">非递归算法</span>:</span></strong>
#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;}


运行结果:

递归算法

#include<iostream>using namespace std;void digui(int low,int high,int a[],int f);int main(){int low=0,high,i=0;int f,a[50],n;cin>>n>>f;while(i<n){cin>>a[i];i++;}high=n-1;digui(low,high,a,f);return 0;}void digui(int low,int high,int a[],int f){int mid;mid=(high-low)/2;if(low<=high){if(a[mid]==f){cout<<"find in "<<mid+1;}else if(a[mid]<f){digui(mid+1,high,a,f);}else{digui(low,mid-1,a,f);}}if(low>high)cout<<"not find"<<endl;}


运行结果:

学习心得:

折半查找在查找中省去了不少步,简便易懂了很多。

 

0 0
原创粉丝点击