Based on this fairly simple code based on the sort package. The response index of o1
is invalid as pointed by @JimB because a bigger or equals operator is required for binary search
l := []string{"o1", "o2", "o3"}
i1 := sort.Search(len(l), func(i int) bool { return strings.EqualFold(l[i], "o1") })
fmt.Println("o1:", i1) //PRINTS 3 - WRONG
https://play.golang.org/p/nUs-ozTYsY
The working solution is:
l := []string{"o1", "o2", "o3"}
i1 := sort.Search(len(l), func(i int) bool { return l[i] >= "o1" })
fmt.Println("o1:", i1)
https://play.golang.org/p/WRsijy_xzV
However this still it's important to bare in mind a important last check. The return value is the index to insert x
, which means that you can end up with something like:
o1: 0 (index 0)
o2: 1
o3: 2
o777: 0 (Same 0 index!)
Therefore it's important as pointed by @JimB to check for data[i] == 23
separately.
if i < len(data) && ---> data[i] == x <--- {
x is present at data[i]
} else {
...
}
A binary search requires a greater than or less than comparison, otherwise it would just be a linear search over the slice. Any comparison greater than the value at the requested index needs to be true, in order for the search method to scan backwards looking for the smallest index.
See the default implementation of the string search function from the sort package:
https://golang.org/src/sort/search.go?s=3673:3717#L91
func SearchStrings(a []string, x string) int {
return Search(len(a), func(i int) bool { return a[i] >= x })
}