Skip to content

Commit 2d5a8ea

Browse files
committed
Update binary_search.md
1 parent 8eb68ae commit 2d5a8ea

1 file changed

Lines changed: 3 additions & 3 deletions

File tree

src/num_methods/binary_search.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ Then the implementation could look like this:
6060
... // a sorted array is stored as a[0], a[1], ..., a[n-1]
6161
int l = -1, r = n;
6262
while (r - l > 1) {
63-
int m = l + (r - l) / 2;
63+
int m = (l + r) / 2;
6464
if (k < a[m]) {
6565
r = m; // a[l] <= k < a[m] <= a[r]
6666
} else {
@@ -71,7 +71,7 @@ while (r - l > 1) {
7171

7272
During the execution of the algorithm, we never evaluate neither $A_L$ nor $A_R$, as $L < M < R$. In the end, $L$ will be the index of the last element that is not greater than $k$ (or $-1$ if there is no such element) and $R$ will be the index of the first element larger than $k$ (or $n$ if there is no such element).
7373

74-
**Note.** If one calculates `m` as follows `m = (r + l) / 2` it can lead to overflow. It is funny fact that this error lived about 9 years in JDK as described in the [blogpost](https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html).
74+
**Note.** Calculating `m` as `m = (r + l) / 2` can lead to overflow if `l` and `r` are two positive integers, and this error lived about 9 years in JDK as described in the [blogpost](https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html). Some alternative approaches include e.g. writing `m = l + (r - l) / 2` which always works for positive integer `l` and `r`, but might still overflow if `l` is a negative number. If you use C++20, it offers an alternative solution in the form of `m = std::midpoint(l, r)` which always works correctly.
7575

7676
## Search on arbitrary predicate
7777

@@ -91,7 +91,7 @@ Proof of correctness supposing a transition point exists, that is $f(0)=0$ and $
9191
... // f(i) is a boolean function such that f(0) <= ... <= f(n-1)
9292
int l = -1, r = n;
9393
while (r - l > 1) {
94-
int m = l + (r - l) / 2;
94+
int m = (l + r) / 2;
9595
if (f(m)) {
9696
r = m; // 0 = f(l) < f(m) = 1
9797
} else {

0 commit comments

Comments
 (0)