Library contents

Go slices.BinarySearch

slices.BinarySearch searches an ascending slice and returns the earliest matching index or the position where the target would fit.

A simple example

slices.BinarySearch

  1. Start with Sorted values 1, 3, 5
  2. Do this Search for 3
  3. Result Found in the middle
A comparison with the middle value is enough to locate 3.

Syntax

Go syntax
index, found := slices.BinarySearch(sorted, target)
Run this example in Go

Save the program as main.go. Use Go 1.21 or later.

go run main.go

Find a lookup key or its insertion point

A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.

From the programprices := []int{10, 20, 20, 40}
First output line1 true
main.go
package main

import (
	"fmt"
	"slices"
)

func main() {
	prices := []int{10, 20, 20, 40}
	for _, target := range []int{20, 25, 50} {
		index, found := slices.BinarySearch(prices, target)
		fmt.Println(index, found)
	}
}
Output
1 true
3 false
4 false

The index can equal len(sorted). Read the indexed element only after checking found or establishing that the index lies inside the slice.

Go documentation for slices.BinarySearch

Advertisements

Locate a numbered tote

A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?

Given4 · 9 · 15 · 22 | seek 15
Worked result2

Find the earliest permit

A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?

Given3 · 6 · 10 | seek 3
Worked result0