sorthelper

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 27, 2022 License: Apache-2.0 Imports: 0 Imported by: 3

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Find added in v0.12.0

func Find(n int, cmp func(int) int) (i int, found bool)

Find uses binary search to find and return the smallest index i in [0, n) at which cmp(i) <= 0. If there is no such index i, Find returns i = n. The found result is true if i < n and cmp(i) == 0. Find calls cmp(i) only for i in the range [0, n).

To permit binary search, Find requires that cmp(i) > 0 for a leading prefix of the range, cmp(i) == 0 in the middle, and cmp(i) < 0 for the final suffix of the range. (Each subrange could be empty.) The usual way to establish this condition is to interpret cmp(i) as a comparison of a desired target value t against entry i in an underlying indexed data structure x, returning <0, 0, and >0 when t < x[i], t == x[i], and t > x[i], respectively.

For example, to look for a particular string in a sorted, random-access list of strings:

i, found := sort.Find(x.Len(), func(i int) int {
    return strings.Compare(target, x.At(i))
})
if found {
    fmt.Printf("found %s at entry %d\n", target, i)
} else {
    fmt.Printf("%s not found, would insert at %d", target, i)
}

Types

type CustomSortable added in v0.12.0

type CustomSortable struct {
	LessFunc func(i, j int) bool
	SwapFunc func(i, j int)
	LenFunc  func() int
}

func (CustomSortable) Len added in v0.12.0

func (s CustomSortable) Len() int

func (CustomSortable) Less added in v0.12.0

func (s CustomSortable) Less(i, j int) bool

func (CustomSortable) Swap added in v0.12.0

func (s CustomSortable) Swap(i, j int)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL