go/src/sort
David R. Jenni fd37b8ccf2 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 <gri@golang.org>
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2017-02-06 17:08:13 +00:00
..
example_interface_test.go
example_keys_test.go
example_multi_test.go
example_search_test.go sort: fix search descending order example 2016-09-17 00:14:19 +00:00
example_test.go sort: add Slice example 2016-12-01 05:43:05 +00:00
example_wrapper_test.go
export_test.go
genzfunc.go sort: add Slice, SliceStable, and SliceIsSorted 2016-10-03 16:09:56 +00:00
search.go sort: optimize average calculation in binary search 2017-02-06 17:08:13 +00:00
search_test.go
sort.go sort: add Slice, SliceStable, and SliceIsSorted 2016-10-03 16:09:56 +00:00
sort_test.go sort: fix a slice benchmark not using the stable variant, add another 2016-10-05 14:43:23 +00:00
zfuncversion.go sort: add Slice, SliceStable, and SliceIsSorted 2016-10-03 16:09:56 +00:00