顺序表应用6:有序顺序表查询
Description
顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input
第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Samples
Sample #1
Input
10
1 22 33 55 63 70 74 79 80 87
4
55 10 2 87
Output
4
No Found!
No Found!
10
分析:
二分查找法,
错了好几次,最后发现是因为把错误条件返回值写成了return 0,服了
#include <bits/stdc++.h>
using namespace std;
#define MAX 10000
int a[100010],b[10010],c[20010];
int n,x,t,m;
//二分查找
int find(int a[],int l,int r,int x){if(l<=r){int m=(l+r)/2;if(a[m]==x)return m+1;if(a[m]>x)return find(a,l,m-1,x);if(a[m]<x)return find(a,m+1,r,x);}elsereturn -1;
}
int main(){cin>>n;for(int i=0;i<n;i++)cin>>a[i];cin>>t;while(t--){cin>>x;int r=find(a,0,n-1,x);if(r==-1)cout<<"No Found!"<<endl;elsecout<<r<<endl;}return 0;
}