Slices BinarySearch And Sorted Insert
Search a sorted slice with slices.BinarySearch, which returns both the match position and a found flag, then insert at that position to keep the order.
Code
package main
import (
"fmt"
"slices"
)
func main() {
ids := []int{7, 19, 42, 88}
// BinarySearch 返回 (插入位置, 是否精确命中)
pos, found := slices.BinarySearch(ids, 42)
fmt.Println("find 42:", pos, found)
pos, found = slices.BinarySearch(ids, 50)
fmt.Println("find 50:", pos, found)
// 未命中时 pos 就是保持有序的插入点
if !found {
ids = slices.Insert(ids, pos, 50)
}
fmt.Println("after insert:", ids)
pos, found = slices.BinarySearch(ids, 50)
fmt.Println("find 50 again:", pos, found)
}Inside the snippet
Count the function main as the entire surface area of Slices BinarySearch And Sorted Insert.
Putting it to use
The demo output is labeled (find 42:, find 50:, after insert:), so the printed output reads as a trace of the operations performed.
Core lines
pos, found := slices.BinarySearch(ids, 42)
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 Slices BinarySearch And Sorted Insert print when run?
- Run it as a complete program — the output lines carry labels such as `find 42:`, `find 50:`, `after insert:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.