Skip to content

Commit fd37b8c

Browse files
davidrjennigriesemer
authored andcommitted
sort: optimize average calculation in binary search
Use fewer instructions to calculate the average of i and j without overflowing at the addition. Even if both i and j are math.MaxInt{32,64}, the sum fits into a uint{32,64}. Because the sum of i and j is always ≥ 0, the right shift by one does the same as a division by two. The result of the shift operation is at most math.MaxInt{32,64} and fits again into an int{32,64}. name old time/op new time/op delta SearchWrappers-4 153ns ± 3% 143ns ± 6% -6.33% (p=0.000 n=90+100) This calculation is documented in: https://research.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html Change-Id: I2be7922afc03b3617fce32e59364606c37a83678 Reviewed-on: https://go-review.googlesource.com/36332 Reviewed-by: Robert Griesemer <[email protected]> Run-TryBot: Robert Griesemer <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 91ad2a2 commit fd37b8c

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

src/sort/search.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func Search(n int, f func(int) bool) int {
6161
// Invariant: f(i-1) == false, f(j) == true.
6262
i, j := 0, n
6363
for i < j {
64-
h := i + (j-i)/2 // avoid overflow when computing h
64+
h := int(uint(i+j) >> 1) // avoid overflow when computing h
6565
// i ≤ h < j
6666
if !f(h) {
6767
i = h + 1 // preserves f(i-1) == false

0 commit comments

Comments
 (0)