-
Notifications
You must be signed in to change notification settings - Fork 77
/
binary_search.cpp
47 lines (44 loc) · 1.2 KB
/
binary_search.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
int lowerBound(vector<int>& arr, int target) {
int n = (int)arr.size();
int left = 0, right = n - 1;
int indx = -1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(arr[mid] == target) {
indx = mid;
}
if(arr[mid] < target) {
left = mid + 1;
} else { // arr[mid] >= target
right = mid - 1;
}
}
return indx;
}
// different from C++ upper_bound. return target's index inclusive
int upperBound(vector<int>& arr, int target) {
int n = (int)arr.size();
int left = 0, right = n - 1;
int indx = -1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(arr[mid] == target) {
indx = mid;
}
if(arr[mid] <= target) {
left = mid + 1;
} else { // arr[mid] > target
right = mid - 1;
}
}
return indx;
}
pair<int, int> equalRange(vector<int>& arr, int target) {
int lbound = lowerBound(arr, target);
int ubound = upperBound(arr, target);
return pair<int, int>{lbound, ubound};
}
int binarySearch(vector<int>& arr, int target) {
int lbound = lowerBound(arr, target);
return lbound;
}