-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_extend.cpp
More file actions
78 lines (59 loc) · 1.14 KB
/
binary_search_extend.cpp
File metadata and controls
78 lines (59 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
WAP that takes an array of size n and q queries as input.
For each query you will be given a number. For each query you have to print ‘YES’
if the number is present in the array, otherwise print ‘No’.
Solve this problem in an optimized way.
Sample input
5
6 3 2 1 8
4
1
5
2
9
Sample output
YES
NO
YES
NO
*/
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<string>
using namespace std;
void binary_search_query(vector<int> arr,int key){
int i = 0;
int j = arr.size() - 1;
bool flag = false;
while(i<=j){
int mid = (i+j)/2;
if(arr[mid] == key){
flag = true;
break;
}
else if(arr[mid] < key)
i = mid+1;
else if (arr[i] > key)
j = mid-1;
}
(flag)? cout << "YES" << endl : cout << "NO" << endl;
}
int main(){
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i<n; i++){
cin >> arr[i];
}
sort(arr.begin(),arr.end());
int q;
cin >> q;
while(q--){
int a;
cin >> a;
binary_search_query(arr,a);
}
return 0;
}