A generic simple binary search library to allow finding the index of any element in an ordered slice of comparable elements
Make sure to have Go installed (Version 1.18
or higher).
Install search
with go get
:
$ go get -u github.com/imbue11235/search
Using constraints.Ordered
Search slices of primitive types like int, float etc.
search.Slice([]int{1, 2, 3, 4, 5, 6}, 2) // => index: 1
Using search.Comparable[T]
Search slices of custom structs
type ComparableStruct struct {
value int
}
func (c ComparableStruct) CompareTo(other ComparableStruct) int {
return c.value - other.value
}
element := ComparableStruct{2}
list := []ComparableStruct{{1}, {2}, {3}, {4}, {5}, {6}}
search.ComparableSlice(list, element) // => index: 1
This project is licensed under the MIT license.