1. 程式人生 > >golang sort包使用

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