-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatNhiPhan.cpp
58 lines (49 loc) · 1.17 KB
/
ChatNhiPhan.cpp
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
#include <iostream>
using namespace std;
int binarySearch(int a[], int n, int x) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (a[mid] == x) {
while (mid > 0 && a[mid - 1] == x) {
mid--;
}
return mid;
}
if (a[left] <= a[mid]) {
if (a[left] <= x && x < a[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (a[mid] < x && x <= a[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
int main() {
#ifndef a
freopen("intput.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n; cin >> n;
int a[n];
for(int &x : a) {
cin >> x;
}
int x;
cin >> x;
int result = binarySearch(a,n,x);
if (result != -1) {
cout << "tim thay " << x << " o vi tri" << result;
} else {
cout << "ko tim thay";
}
return 0;
}