//二分法查找
#include <iostream>
using namespace std;
int main()
{
int a[15];
int n,i,num,top,mid,bott,local;
bool flag=true,sign;
char c;
cout<<"你要输入多少个数?";
cin>>n;
cout<<"请从小到大输入你要的"<<n<<"个数字: "<<endl;
for (i=0;i<n;i++)
cin>>a[i];
//交互框架
while (flag)
{
cout<<"请输入你要查找的数字:";
cin>>num;
top=0;
bott=n-1;
if ((num<a[0])||(num>a[n-1])) local=-1;
sign=false;
//二分法查找
while ((!sign)&&(top<=bott))
{
mid=(top+bott)/2;
if (num==a[mid])
{
local=mid;
cout<<"这个数已经找到!"<<"他在第"<<local+1<<"位!"<<endl;
sign=true;
}
else if (num<a[mid]) bott=mid-1;
else top=mid+1;
}
//加入没找到时
if ((!sign)&&(local==-1)) cout<<"这个数字不存在!"<<endl;
//交互框架
cout<<"你是否要继续查找其他数字?(Y/N) ";
cin>>c;
if (c=='N'||c=='n') flag=false;
}
return 0;
}
//二分法(递归版)
#include <stdio.h>
int main()
{
int a[10];
void erfen(int a[],int,int,int);
int i,x;
scanf("%d",&x);
for (i=0;i<5;i++)
scanf("%d",&a[i]);
erfen(a,x,0,4);
return 0;
}
void erfen(int a[],int x,int top,int bott)
{
int mid=(top+bott)/2;
if (x==a[mid]&&top<=bott) printf("它在第%d位\n",mid+1);
else if (x>a[mid]&&top<=bott) erfen(a,x,mid+1,bott);
else if (x<a[mid]&&top<=bott)erfen(a,x,top,mid-1);
else printf("找不到这个数\n");
}