Go slices.BinarySearch
slices.BinarySearch searches an ascending slice and returns the earliest matching index or the position where the target would fit.
A simple example
slices.BinarySearch
- Start with Sorted values 1, 3, 5
- Do this Search for 3
- Result Found in the middle
Syntax
index, found := slices.BinarySearch(sorted, target)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Find a lookup key or its insertion point
A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.
package main
import (
"fmt"
"slices"
)
func main() {
prices := []int{10, 20, 20, 40}
for _, target := range []int{20, 25, 50} {
index, found := slices.BinarySearch(prices, target)
fmt.Println(index, found)
}
}
1 true 3 false 4 false
The index can equal len(sorted). Read the indexed element only after checking found or establishing that the index lies inside the slice.
Go documentation for slices.BinarySearch
Locate a numbered tote
A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?
Find the earliest permit
A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?