Search code examples
algorithmsortinggobinary-search

BinarySearch in sort package


I am looking at this function in Go sort package" func SearchInts(a []int, x int) int and curious if there is a straight forward way to identify if an element exists in the slice or not?

In Java Arrays.binarySearch(..) simply returns a negative value. I am curious if golang's api func SearchInts(a []int, x int) reports if x doesn't exist? not sure why func SearchInts(a []int, x int) doesn't return two values (index,isPresent)?


Solution

  • You can simply check:

    i := sort.SearchInts(slice, value)
    if i<len(slice) && slice[i]==value {
       // It exists
    }