@@ -40,3 +40,92 @@ while (left<right)
4040}
4141酌情选用。
4242```
43+
44+
45+
46+ @小白二号
47+
48+ - 在一个有序的数组中寻找某个值
49+
50+ ``` c++
51+ int bsearch (int* A, int n, int k) {
52+ int left = -1, right = n;
53+ while (right - left > 1) {
54+ int mid = (left + right) / 2;
55+ if (A[ mid] == k) {
56+ return mid;
57+ } else if (A[ mid] < k) {
58+ left = mid;
59+ } else {
60+ right = mid;
61+ }
62+ }
63+ return -1;
64+ }
65+ ```
66+
67+ - 满足judge(x)=true的最大值
68+
69+ ```c++
70+ bool judge(int x) {}
71+ int bsearch(int min, int max) {
72+ int left = min, right = max;
73+ //这里为什么要right++呢,因为我们求的是上界,二分区间中,left要满足f(x),并且尽可能大
74+ //需要要保证left在[min, max]遍历到
75+ //终止条件是right - left > 1,所以right需要+1确保left能取到min
76+ right++;
77+ while (right - left > 1) {
78+ int mid = (left + right) / 2;
79+ if (judge(mid)) {
80+ left = mid;
81+ } else {
82+ right = mid;
83+ }
84+ }
85+ return left;
86+ }
87+ ```
88+
89+ - 满足judge(x)=true的最小值
90+
91+ ``` c++
92+ bool judge (int x) {}
93+ int bsearch(int min, int max) {
94+ int left = min, right = max;
95+ //这里为什么要left--呢,因为我们求的是下界,二分区间中,right要满足f(x),并且尽可能小
96+ //需要要保证right在[ min, max] 遍历到
97+ //终止条件是right - left > 1,所以left需要-1确保right能取到max
98+ left--;
99+ while (right - left > 1) {
100+ int mid = (left + right) / 2;
101+ if (judge(mid)) {
102+ right = mid;
103+ } else {
104+ left = mid;
105+ }
106+ }
107+ return right;
108+ }
109+ ```
110+
111+ - 浮点数,求f(x)在[min,max]的零点
112+
113+ ```c++
114+ const double EPS = 1e-8;
115+ double cal(double x) {} //假定是单调增
116+ //这里需要保证区间有零点
117+ double bsearch(double min, double max) {
118+ double left = min, right = max;
119+ while (right - left > EPS) {
120+ double mid = (left + right) / 2;
121+ if (A[mid] == 0) {
122+ return mid;
123+ } else if (cal(mid) < 0) {
124+ left = mid;
125+ } else {
126+ right = mid;
127+ }
128+ }
129+ return (left + right) / 2;
130+ }
131+ ```
0 commit comments