I’m using sort.SearchStrings to find element in a slice (slice is sorted in ascending order, as requested sort.SearchStrings…) and I have an incorrect solution
package main
import ( "fmt" "sort" )
func main() {
// Slice is sorted in ascending order, as requested sort.SearchStrings
Slice := []string{"1ZzLBmxsdbKiab9qcKKutMAnNGpYnLtmc",
"1ZzT38aAMzaCo8SsB1tV2qgPA9BsbMcc5",
"1zZf3HNcG4vSd6LwktYGk1SkXRk65cps6",
}
fmt.Println(sort.SearchStrings(Slice, "1ZzT38aAMzaCo8SsB1tV2qgPA9BsbMcc4"))
} // Show 1. Should show 3
I expected 3 (len of slice, because string not in slice), but the actual output is 1.
I just had a quick read over the documentation for sort.SearchStrings which suggests the following:
SearchStrings searches for x in a sorted slice of strings and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.
As you rightly say, the search string does not exist in the sorted set, knowing this, if you note the above quote from the documentation, in an instance whereby the searched string does not exist, the value returned is the index where the search string would be inserted to maintain the sort order, which in your case is 1.
If you change your search string to the following (replacing the 4 with a 7)
1ZzT38aAMzaCo8SsB1tV2qgPA9BsbMcc7
The returned value from the SearchStrings call would be 2 as this value would need to be appended to the sorted set to maintain the sort order.