Consider the following example:
package main
import (
"fmt"
"sort"
)
func main() {
var n int
var a sort.IntSlice
a = append(a, 23)
a = append(a, 3)
a = append(a, 10)
sort.Sort(a)
fmt.Println(a)
n = sort.SearchInts(a, 1)
fmt.Println(n)
n = sort.SearchInts(a, 3)
fmt.Println(n)
}
http://play.golang.org/p/wo4r43Zghv
And the result is:
[3 10 23]
0
0
How am I supposed to know if the number is present in the slice or not, when both the first element and the nonexistent element return 0 as index?
Update
Note that the index can also be greater than the length of the slice so the proper way to find if an element is present in the slice is:
num := 1
n = sort.SearchInts(a, num)
if n < len(a) && a[n] == num {
// found
}
Check whether the number you were looking for actually lives at the returned index. The binary search routines in
sortare supposed to find the index where a value can be inserted if it’s not already present.E.g. a search for 100 in the slice in your example will return 3 because the value must be appended to the slice.