描述
给定一个单调递增的整数序列,问某个整数是否在序列中。
输入
第一行为一个整数n,表示序列中整数的个数;第二行为n(n不超过10000)个整数;第三行为一个整数m(m不超过50000),表示查询的个数;接下来m行每行一个整数k。
输出
每个查询的输出占一行,如果k在序列中,输出所在数组下标,否则输出not exit。
#include<iostream>
using namespace std;
int flag = 0;
int m; //待找数
//递归
int binarysearch(int a[],int l,int r)
{
if (flag)
return -1;
int temp;
int t1, t2;
if(l <= r)
{
temp = (l+r)/2;
if(a[temp] == m)
return temp;
else
{
if(a[temp] < m)
t1 = binarysearch(a,temp+1,r);
else
t2 = binarysearch(a,l,temp-1);
}
}
if (a[t1] == m || a[t2] == m) return a[t1] == m ? t1 : t2;
return -1;
}
//循环
int binarysearchs(int a[],int n)
{
int l = 0,r = n-1;
int temp;
while(l <= r)
{
temp = (l+r)/2;
if(a[temp] == m)
return temp;
else
if(a[temp] < m)
l = temp+1;
else
r = temp-1;
}
return -1;
}
void output(int a)
{
if(a == -1)
cout<<"not exist"<<endl;
else
cout<<a<<endl;
}
int main()
{
int n; //输入数据大小
int a[10000]; //存储有序数组
cin>>n;
for(int i = 0;i < n;i++)
{
cin>>a[i];
}
cin>>m;
int num1 = binarysearch(a,0,n-1);
int num2 = binarysearchs(a,n);
output(num1);
output(num2);
return 0;
}