← 中文资源

简体中文版本

sort.Search 定位插入点

sort.Search 在有序数据上返回第一个满足谓词的索引,没有匹配则返回长度 n;谓词必须单调,用它定位插入点时要先比对 n 防止越界。

阅读英文原文

实现说明

sort.Search 定位插入点的核心是函数 main。

使用要点

  • 跑完文件,输出里会留下标记——first >= 50 at index:、missing:。

常见问题

运行「sort.Search 定位插入点」会打印什么?

整个文件跑完,输出行以 first >= 50 at index:、missing: 这类前缀开头。

核心语句

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

代码示例

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)
}