#include <iostream>
#include<string>
#include<ctime>
#include<cstdlib>
#include<algorithm>
using namespace std;
//非递归版本的二分查找法
int BinarySearch1(int a[],int n,int key){
int low=0;
int high=n-1;
int mid;
if(key<a[0]||key>a[n-1])
return -1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid]){
cout<<"查找成功,mid="<<mid<<endl;
return mid;
}
if(key<a[mid])
high=mid-1;
else //key>a[mid] 应该到mid+1 ......high区间去找
low=mid+1;
}
if(low>high){
cout<<"查找失败"<<endl;
return -1;
}
}
int main(){
int *a;
int i=0;
int n,m;
int key;
a=new int[n];
cout<<"请输入n:"<<endl;
cin>>n;
srand((unsigned)time(NULL));
for(i=0;i<n;i++){
m=rand()%100+1;
a[i]=m;
}
sort(a,a+n);
cout<<"长度是"<<n<<"的有序数据列表:"<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
cout<<"输入你要找的key:"<<endl;
cin>>key;
cout<<BinarySearch1(a,n,key);
}
标签:二分,include,cout,int,mid,high,查找,low,数据结构
From: https://blog.51cto.com/u_16202211/7967887