Hi community,
I used sort.Search on a sorted slice in below code started at Line 36, and it worked.
I also tried to call sort.Search in a loop, started at Line 53. It does not seem to work. How can I correct the loop version?
Thanks
---
package main
import (
"log"
"sort"
)
type T struct {
name string
}
func main() {
log.SetFlags(log.LstdFlags | log.Llongfile)
haystack := []T{
// {name: "apple", },
{name: "compote", }, //dup
{name: "orange", },
{name: "compote", }, //dup
}
sort.Slice(haystack, func(i, j int) bool {
if haystack[i].name < haystack[j].name {
return true
} else {
return false
}
})
for _, t := range haystack {
log.Println("sorted", t)
}
needle := T{name: "compote"}
// Style 1: ok, lower upper bounds style // Line 36
/*
lower := sort.Search(len(haystack), func(i int) bool {
})
upper := sort.Search(len(haystack), func(i int) bool {
})
if lower != len(haystack) {
for i := lower; i != upper; i++ {
log.Println("found", i, haystack[i])
}
}
*/
// Style 2: error, loop style // Line 53
for index := 0; index < len(haystack); index++ {
ret := sort.Search(len(haystack[index:]), func(i int) bool {
log.Println(index, ret)
if ret < len(haystack) {
index += ret
log.Println("found", index, haystack[index])
}
}
}