Sort Search Locates Insertion Points

Locate insertion points in sorted data with sort.Search: it returns the first index whose predicate turns true, or the slice length when nothing matches.

GoData Fetching

Code

gosnippet
32 lines
package main

import (
	"fmt"
	"sort"
)

func main() {
	latencies := []int{12, 24, 24, 48, 96, 192}

	// sort.Search returns the smallest i where f(i) is true; f must be monotonic
	// Find the first position >= 50 in sorted data
	idx := sort.Search(len(latencies), func(i int) bool {
		return latencies[i] >= 50
	})
	fmt.Println("first >= 50 at index:", idx, "value:", latencies[idx])

	// When nothing matches it returns len: check before indexing to stay in bounds
	missing := sort.Search(len(latencies), func(i int) bool {
		return latencies[i] >= 1000
	})
	fmt.Println("missing:", missing, "hit end:", missing == len(latencies))

	// Insertion point: where a new element belongs while keeping the order
	pos := sort.Search(len(latencies), func(i int) bool {
		return latencies[i] >= 30
	})
	latencies = append(latencies, 0)
	copy(latencies[pos+1:], latencies[pos:])
	latencies[pos] = 30
	fmt.Println(latencies)
}

What the code does

The moving parts are the function main.

Points of care

  • No install step: all APIs used ship with the platform.

Applying it

The main signature reads func main()

Each run prints the 2 labeled blocks first >= 50 at index:, missing: in source order.

Statements that matter

latencies = append(latencies, 0)
return latencies[i] >= 1000
return latencies[i] >= 50

Interactive Tools for This Topic

FAQ

What does Sort Search Locates Insertion Points print when run?
Invoke the file as-is — the `first >= 50 at index:`, `missing:` prefixes identify which step printed each line.