Standard library / sort

sort.Search()

Binary search for the first true predicate in a false-then-true sequence; returns n if none is true. Expected stdout: '2\n'.

Formal Syntax & Structure

go syntaxgo
func Search(n int, f func(int) bool) int

Parameters & Attributes

NameTypeDescription
nintNumber of candidate indices.
ffunc(int) boolMonotonic predicate: false before the boundary, true at and after it.

Return Value

int

Binary search for the first true predicate in a false-then-true sequence; returns n if none is true.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sort")
func main() {  a := []int{1, 4, 8}  fmt.Println(sort.Search(len(a), func(i int) bool { return a[i] >= 5 }))}
Go Reference