Sort Search Finds First True Index

Locate the first qualifying position with sort.SearchInts and the predicate-based sort.Search, handling the all-true and all-false boundaries yourself.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"sort"
)

func main() {
	// 升序序列里找第一个 >= 25 的下标
	latencies := []int{5, 12, 19, 25, 31, 48}
	i := sort.SearchInts(latencies, 25)
	fmt.Println("first >= 25 at index", i, "value", latencies[i])

	// 任意单调谓词:找第一个错误率超过 1% 的分片
	errRates := []float64{0.001, 0.004, 0.009, 0.012, 0.02}
	j := sort.Search(len(errRates), func(k int) bool {
		return errRates[k] > 0.01
	})
	if j < len(errRates) {
		fmt.Println("first shard over 1% at index", j, "rate", errRates[j])
	} else {
		fmt.Println("no shard over 1%")
	}

	// 谓词全真返回 0、全假返回 n —— 边界由调用方处理
	fmt.Println("all false ->", sort.Search(len(errRates), func(int) bool { return false }))
	fmt.Println("all true  ->", sort.Search(len(errRates), func(int) bool { return true }))
}

How it works

Count the function main as the entire surface area of Sort Search Finds First True Index.

Applying it

Running the file prints labeled results such as first >= 25 at index, first shard over 1% at index, no shard over 1% — each operation’s effect is visible in the output.

Statements that matter

return errRates[k] > 0.01

Interactive Tools for This Topic

FAQ

What does Sort Search Finds First True Index print when run?
The script runs standalone; its 5 labeled outputs include `first >= 25 at index`, `first shard over 1% at index`, `no shard over 1%`.