slices.IsSorted Validates Ordering

Check ordering invariants with slices.IsSorted and IsSortedFunc before binary searching, so unsorted input is caught instead of producing wrong results.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"slices"
	"strings"
)

type Server struct {
	Name string
	Load int
}

func main() {
	ids := []int{3, 7, 11, 19}
	fmt.Println("ids sorted:", slices.IsSorted(ids))

	// IsSortedFunc:按自定义键检查(名称升序)
	servers := []Server{
		{"api", 40},
		{"billing", 90},
		{"auth", 10},
	}
	byName := func(a, b Server) int { return strings.Compare(a.Name, b.Name) }
	fmt.Println("servers sorted by name:", slices.IsSortedFunc(servers, byName))

	// 二分查找前先保证有序:乱序数据会得到错误结果
	slices.SortFunc(servers, byName)
	fmt.Println("after sort:", slices.IsSortedFunc(servers, byName))
}

Inside the snippet

Structurally, expect the function main and nothing else.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

Entry signature: func main()

Look for the ids sorted:, servers sorted by name:, after sort: prefixes when the file runs; they tie each line to its step.

Core lines

byName := func(a, b Server) int { return strings.Compare(a.Name, b.Name) }

Interactive Tools for This Topic

FAQ

What does slices.IsSorted Validates Ordering print when run?
No setup needed: run the file and look for labeled lines like `ids sorted:`, `servers sorted by name:`, `after sort:` in the output.