Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort.Search, looking for a number that is not in the slice

Tags:

go

I currently have a problem in my project where i must find numbers that are not present in a slice. I found working code in the golang website, this works great. In my project i make a empty block and let the else statement do all the work. I tried to alter the code to remove the empty block but i got errors every time, i finaly found a example that reproduces the problem :

package main

import (
    "fmt"
    "sort"
)

func main() {
    data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
    nr := 9
    sort.Ints(data)
    index := sort.Search(len(data), func(index int) bool { return data[index] == nr })
    if index == len(data) {
        fmt.Print("It's not in : ")
        fmt.Println(nr)
    } else {
        fmt.Print("It's in! Index is at : ")
        fmt.Println(index)
    }
}

Working code on golang playground!

like image 259
Dippo Avatar asked Sep 12 '25 13:09

Dippo


1 Answers

I encounter the same problem too, because I misunderstood the document in godoc sort Search.

If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.

I thought that means "The documentation says that == is allowed" too. In fact, in the function as a parameter in sort.Search, can only use >= or <=, no ==. And that sentence means after you got the index i, you have to test it with data[i] == 23 to make sure 23 is in the slice.

like image 179
Ahui Avatar answered Sep 14 '25 04:09

Ahui