-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZ_Binary_Search.cpp
More file actions
38 lines (29 loc) · 920 Bytes
/
Copy pathZ_Binary_Search.cpp
File metadata and controls
38 lines (29 loc) · 920 Bytes
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
#include <bits/stdc++.h>
using namespace std;
bool binarySearch(long long arr[], long long start, long long end, long long search) {
if (start > end) { // Base case: If range is invalid, element is not found
return false;
}
long long mid = start + (end - start) / 2; // Avoid overflow in mid calculation
if (arr[mid] == search) {
return true; // Element found
} else if (arr[mid] < search) {
return binarySearch(arr, mid + 1, end, search); // Search in the right half
} else {
return binarySearch(arr, start, mid - 1, search); // Search in the left half
}
}
int main() {
int x, y;
cin >> x >> y;
long long arr[x];
for (int i = 0; i < x; i++) {
cin >> arr[i];
}
while (y--) {
long long n;
cin >> n;
cout << (binarySearch(arr, 0, x - 1, n) ? "found" : "not found") << endl;
}
return 0;
}