# 王道机试例题3.5 查找

## 示例1

### 输入

5
1 5 2 4 3
3
2 5 6


### 输出

YES
YES
NO


# 代码

#include <iostream>
#include<stdio.h>

const int maxn = 100;
int arr1[maxn];
int arr2[maxn];

bool search(int x,int n) {    //二分查找
int left=0, right=n-1, mid;
mid = (left + right) / 2;
while (left <= right) {
if (arr1[mid] == x) {
return true;
}
else if (arr1[mid] > x) {
right = mid - 1;
mid = (left + right) / 2;
}
else {
left = mid + 1;
mid = (left + right) / 2;
}
}
return false;
}

int main()
{
int n,m;
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%d", &arr1[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &arr2[i]);
}
//多次查找，二分查找的性能会优于线性查找
//排序 升序
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > i; j--) {
if (arr1[j] < arr1[j - 1]) {
int temp = arr1[j];
arr1[j] = arr1[j - 1];
arr1[j - 1] = temp;
}
}
}
for (int i = 0; i < m; i++) {
if (search(arr2[i], n)) {
printf("YES\n");
}
else {
printf("NO\n");
}
}
}
}


# 注意

int mid=(left+right)/2。通常情况下，这是对的，也很容易理解。

03-12

03-20
02-10
05-08 866
03-10
03-05 37
03-26 853
02-25 518
02-23 2901
06-29 408
03-04 4039
10-19
07-30 1454
03-11 136