golang sort包使用

 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)
}

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

猜你喜欢

转载自www.cnblogs.com/LC161616/p/9945585.html