Generic Binary Search With sort.Find

Locate a target in sorted data with sort.Find, whose three-way cmp returns the same signs as strings.Compare and reports the exact insert point on a miss.

GoData Integrity

Code

gosnippet
37 lines
package main

import (
	"fmt"
	"sort"
)

var buildKB = []int{12, 40, 95, 160, 260, 410, 640}

// cmp 采用 strings.Compare(target, x[i]) 的符号方向:
// target < x[i] 返回负数,相等返回 0,target > x[i] 返回正数
func compareSize(target int) func(int) int {
	return func(i int) int {
		switch {
		case target > buildKB[i]:
			return 1
		case target < buildKB[i]:
			return -1
		default:
			return 0
		}
	}
}

func main() {
	// 命中:found 为 true,i 就是目标下标
	i, found := sort.Find(len(buildKB), compareSize(260))
	fmt.Println("260:", i, found)

	// 未命中:found 为 false,i 是应插入的位置
	j, present := sort.Find(len(buildKB), compareSize(300))
	fmt.Println("300:", j, present)

	// 比所有元素都小:插入位置为 0
	k, hit := sort.Find(len(buildKB), compareSize(5))
	fmt.Println("5:", k, hit)
}

Where execution goes

Generic Binary Search With sort.Find keeps everything in the functions compareSize and main.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func compareSize(target int) func(int) int

The output carries step markers — 260:, 300:, 5: — when the file runs.

The entry point wires compareSize together — run it once and the whole demo flows.

Core lines

func compareSize(target int) func(int) int {
	return func(i int) int {
		switch {
		case target > buildKB[i]:
			return 1
		case target < buildKB[i]:
			return -1
		default:
			return 0
		}
	}
}

Interactive Tools for This Topic

FAQ

What does Generic Binary Search With sort.Find print when run?
Running the file directly is enough — expect labeled output lines such as `260:`, `300:`, `5:`.