Standard library / slices

slices.BinarySearch()

Searches an ascending sorted slice; returns the earliest matching index or the insertion index and false. Expected stdout: '1 true\n'.

Formal Syntax & Structure

go syntaxgo
func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)

Parameters & Attributes

NameTypeDescription
xSInput value or collection to process.
targetEValue to find in the ordered collection.

Return Value

(int, bool)

Index and whether an equal value was found.

Working Example

Example Snippetgo
package main
import (  "fmt"  "slices")
func main() {  i, ok := slices.BinarySearch([]int{1, 3, 3, 7}, 3)  fmt.Println(i, ok)}
Go Reference