Sort Search Locates Insertion Points
Locate insertion points in sorted data with sort.Search: it returns the first index whose predicate turns true, or the slice length when nothing matches.
Code
package main
import (
"fmt"
"sort"
)
func main() {
latencies := []int{12, 24, 24, 48, 96, 192}
// sort.Search returns the smallest i where f(i) is true; f must be monotonic
// Find the first position >= 50 in sorted data
idx := sort.Search(len(latencies), func(i int) bool {
return latencies[i] >= 50
})
fmt.Println("first >= 50 at index:", idx, "value:", latencies[idx])
// When nothing matches it returns len: check before indexing to stay in bounds
missing := sort.Search(len(latencies), func(i int) bool {
return latencies[i] >= 1000
})
fmt.Println("missing:", missing, "hit end:", missing == len(latencies))
// Insertion point: where a new element belongs while keeping the order
pos := sort.Search(len(latencies), func(i int) bool {
return latencies[i] >= 30
})
latencies = append(latencies, 0)
copy(latencies[pos+1:], latencies[pos:])
latencies[pos] = 30
fmt.Println(latencies)
}What the code does
The moving parts are the function main.
Points of care
- No install step: all APIs used ship with the platform.
Applying it
The main signature reads func main()
Each run prints the 2 labeled blocks first >= 50 at index:, missing: in source order.
Statements that matter
latencies = append(latencies, 0)
return latencies[i] >= 1000
return latencies[i] >= 50
Interactive Tools for This Topic
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What does Sort Search Locates Insertion Points print when run?
- Invoke the file as-is — the `first >= 50 at index:`, `missing:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.