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.

GoData Integrity

Code

gosnippet
26 lines
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

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:`.