Hi community,
I improved my binary search example with both sort.Search and sort.Find. Please correct me if I got new wrongs with new example. 1. My original question was if there are duplicate entries in sorted slice. After I located the first dup, how can I go to the rest of them without loop. I ever thought using loop was ugly, so I tried to avoid loop. But I think loop is ok. because dups are adjacent on sorted slice. 2. How can I use tuple style comparison found in other languages, like: (a.name, a.num) > (b.name, b.num) struct can be used for == only, not for <, > 3. I think my conditions covered all the cases, but I need an extra trailing return ? Whats the right way to do it? if a < b { return -1 } else if a == b { return 0 } else if a > b { return 1 } return -999 // an extra return Thanks //--- //sort.Search example func sortSearch() { haystack := []T{ {"aaa", 111}, {"bbb", 222}, //dup {"bbb", 222}, //dup {"ccc", 333}, } needle := T{"bbb", 222} index := sort.Search(len(haystack), func(i int) bool { //asc >= //desc <= if haystack[i].name >= needle.name || haystack[i].name == needle.name && haystack[i].num >= needle.num { return true; } return false }) log.Println(index) for i := index; i < len(haystack); i++ { if haystack[i] == needle { log.Println(i, haystack[i]) } else { break } } } //sort.Find example func sortFind() { log.SetFlags(log.LstdFlags | log.Llongfile) haystack := []T{ {"aaa", 111}, {"bbb", 222}, //dup {"bbb", 222}, //dup {"ccc", 333}, } needle := T{"bbb", 222} i, found := sort.Find(len(haystack), func(i int) int { //asc -1 0 1 //desc 1 0 -1 if needle.name < haystack[i].name || needle.name == haystack[i].name && needle.num < haystack[i].num { return -1 } else if needle == haystack[i] { return 0 } else if needle.name > haystack[i].name || needle.name == haystack[i].name && needle.num > haystack[i].num { return 1 } return 9 // do i have to add this line // Line 66 }) log.Println(found, i) for i := i; found && i != len(haystack); i++ { if haystack[i] == needle { log.Println(i, haystack[i]) } else { break } } } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/tencent_9C30B68D792641F2B863FB873EF31B825309%40qq.com.