-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
91 lines (71 loc) · 1.87 KB
/
binary_search.cpp
File metadata and controls
91 lines (71 loc) · 1.87 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
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
/*
* basic binary search algorithm
*
* Complexity:
* Time Complexity : O(logn)
* Space Complexity : O(1)
*/
int binary_search(vector<int> &nums, int target)
{
int start{}, end{(int)nums.size() - 1};
while (start <= end)
{
// prevent overflow
int mid = start + (end - start) / 2;
if (target == nums[mid])
return mid;
else if (target < nums[mid])
end = mid - 1;
else
start = mid + 1;
}
return -1;
}
int lower_bound(vector<int> &nums, int target)
{
int start{}, end{(int)nums.size() - 1};
while (start <= end)
{
// prevent overflow
int mid = start + (end - start) / 2;
if (target <= nums[mid])
end = mid - 1;
else
start = mid + 1;
}
return start;
}
int upper_bound(vector<int> &nums, int target)
{
int start{}, end{(int)nums.size() - 1};
while (start <= end)
{
// prevent overflow
int mid = start + (end - start) / 2;
if (target < nums[mid])
end = mid - 1;
else
start = mid + 1;
}
return start;
}
int main()
{
vector<int> nums{0, 5, 13, 19, 22, 41, 55, 68, 72, 81, 98};
cout << binary_search(nums, 0) << endl; // 0
cout << binary_search(nums, 98) << endl; // 10
cout << binary_search(nums, 68) << endl; // 7
cout << binary_search(nums, -5) << endl; //-1
cout << binary_search(nums, 105) << endl; //-1
cout << lower_bound(nums, 22) << endl; // 4
cout << lower_bound(nums, 20) << endl; // 4
cout << lower_bound(nums, 100) << endl; // 11
cout << upper_bound(nums, 22) << endl; // 5
cout << upper_bound(nums, 20) << endl; // 4
cout << upper_bound(nums, 98) << endl; // 11
// must see it, otherwise RTE
cout << "\n\nNO RTE\n";
return 0;
}