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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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%`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.