Error search element in slice with sort.SearchStrings

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.

1 Like

Hi Frank,

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.

I hope that makes sense

2 Likes

Oh my goodness !!

I read this article

In the section “Binary search” and made me wrong:

“len(a)` if there is no such index.”

I’m sorry for not having read the documentation. Rookie !!

Thank you

1 Like

Haha! No problem at all, happy to help!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.