Standard library / sort
sort.Find()
Binary search for the first index where cmp(i) <= 0, or n. Comparator signs must transition from positive to zero to negative (any region can be empty). Found reports equality. Expected stdout: '1 true\n'.
Formal Syntax & Structure
go syntaxgo
func Find(n int, cmp func(int) int) (i int, found bool)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| n | int | Number of candidate indices. |
| cmp | func(int) int | Index-to-target comparison: positive before the target, zero at matches, negative after the target. |
Return Value
(i int, found bool)
Binary search for the first index where cmp(i) <= 0, or n. Comparator signs must transition from positive to zero to negative (any region can be empty). Found reports equality.
Working Example
Example Snippetgo
package main
import ( "cmp" "fmt" "sort")
func main() { a := []int{1, 4, 4, 9} i, ok := sort.Find(len(a), func(i int) int { return cmp.Compare(4, a[i]) }) fmt.Println(i, ok)}