一、题目描述:
二分查找{-36,-25,0,12,14,29,35,47,76,100},对上述十个数进行二分查找
二、输入样例:
请输入您要查找的数据:
14
-25
121
二、输出样例:
14是第5个数,查找次数为1
-25是第2个数,查找次数为2
查找失败
四、代码实现:
#include <iostream>
#include <algorithm>
using namespace std;
int count_time=0; //查找次数定义为全局变量
int binarySearch(int a[],int n,int key){
int left=0,right=n-1;
while(left<=right){
count_time++; //循环一次,即查找次数+1
int mid=(left+right)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
right=mid-1;
else
left=mid+1;
}
return -1; //未查找到,返回-1
}
int main()
{
int a[10]={-36,-25,0,12,14,29,35,47,76,100};
int key=0;
cout<< "请输入您要查找的数据:"<<endl;
while(cin>>key){
int ans=binarySearch(a,10,key); //返回的是下标,如果是第?个,要下标+1
if(ans>=0)
cout <<key<<"是第"<<ans+1<<"个数,查找次数为"<<count_time<<endl;
else cout<<"查找失败"<<endl;
count_time=0;
}
system("pause");
return 0;
}