Binary search
Binary search finds a target in a sorted slice by repeatedly discarding half of the remaining range. It uses O(log n) comparisons. In Go you write the loop or call slices.BinarySearch / sort.Search.
Detailed Explanation
A linear scan of a million sorted IDs can take a million comparisons. Binary search takes about twenty. You compare the midpoint, then throw away the half that cannot contain the target. The invariant: if the target exists, it lies in [lo, hi).
The midpoint. mid := lo + (hi-lo)/2 avoids overflow that (lo+hi)/2 can hit in other languages. In Go, int is 64-bit on servers, so overflow is rare, but the form is still the one to write. When s[mid] < target, the target is in [mid+1, hi). When s[mid] > target, it is in [lo, mid). Equal: return mid.
sort.Search encodes a predicate. You pass func(i int) bool that is false for a prefix and true for the rest. The return is the first true index, or n if none. Lower bound is sort.Search(n, func(i int) bool { return s[i] >= target }). Upper bound uses >.
slices.BinarySearch returns (index, found). The slice must be sorted in increasing cmp.Ordered order. BinarySearchFunc takes a comparison against the target.
Unsorted input does not panic. It returns a wrong index. Sort first, or do not use binary search. Duplicates: plain search may return any match. Use lower/upper bound when you need the first or last.
Search the answer. Some problems binary-search a numeric range ("minimum capacity that works") rather than an index. The predicate is "can we ship with capacity mid?" The same lo/hi structure applies.
What it costs. O(log n) time, O(1) extra space iteratively. Recursion is unnecessary in Go. For n below a few dozen, linear search is often as fast and simpler.
Code Examples
package main
import (
"fmt"
"slices"
)
func search(s []int, target int) int {
lo, hi := 0, len(s)
for lo < hi {
mid := lo + (hi-lo)/2
switch {
case s[mid] < target:
lo = mid + 1
case s[mid] > target:
hi = mid
default:
return mid
}
}
return -1
}
func main() {
s := []int{1, 3, 4, 7}
fmt.Println(search(s, 4), slices.BinarySearch(s, 4))
}import "sort"
func lowerBound(s []int, target int) int {
return sort.Search(len(s), func(i int) bool {
return s[i] >= target
})
}Common Gotchas
An inconsistent mid update loops forever
always shrink the range (`mid+1` or `hi = mid`), never `lo = mid` with `lo < hi` on integers unless you handle the last element separately.
The slice must be sorted in the same order as the comparisons
descending data needs a matching predicate.
`sort.Search` returns `n` on a miss
using that index without a bounds check panics.
Duplicates need lower/upper bound
a single hit is any of the equal run.