golang sort包使用

时间:2021-10-21 08:20:26

https://studygolang.com/static/pkgdoc/pkg/sort.htm#StringSlice.Search

package main

import (
"fmt"
"sort"
) type StringSlice []string func (this StringSlice) len() int {
return len(this)
} func (this StringSlice) less(i, j int) bool {
return this[i] > this[j]
} func (this StringSlice) swap(i, j int) {
this[i], this[j] = this[j], this[i]
} func (this StringSlice) search(str string) int {
return sort.SearchStrings(this, str)
} func main() {
var str = StringSlice{"123", "999", "345", "987"} fmt.Println(str) sort.Strings(str) var index = str.search("999") fmt.Println(index) fmt.Println(str)
}

golang sort包使用

内部实现 https://github.com/golang/go/blob/master/src/sort/search.go?name=release#112

golang sort包使用