[pkg] sort
常用方法
func main() {
nums := []int{45, 20, 35, 30, 75, 60, 50, 25}
sort.Ints(nums)
fmt.Println(nums) // [20 25 30 35 45 50 60 75]
fmt.Println(sort.SearchInts(nums, 30)) // 2
// can get the index even if not found
fmt.Println(sort.SearchInts(nums, 22)) // 1
fmt.Println(sort.SearchInts(nums, 40)) // 4
fmt.Println(sort.SearchInts(nums, 88)) // 8
brands := []string{"Apple", "Samsung", "LG", "Philips"}
sort.Strings(brands)
fmt.Println(brands) // [Apple LG Philips Samsung]
fmt.Println(sort.SearchStrings(brands, "LG")) // 1
}
反向排序
keywords: sort.Reverse()
func main() {
numbers := []int{1, 5, 3, 6, 2}
sort.Ints(numbers)
fmt.Println(numbers) // [1 2 3 5 6],ascending
sort.Sort(sort.Reverse(sort.IntSlice(numbers)))
fmt.Println(numbers) // [6 5 3 2 1],descending
}
客製化欄位
keywords: sort.Sort()
sort.Interface
只要有實作 sort.Interface
的 slice of structs 都可以使用 sort.Sort()
進行排序:
// https://tutorialedge.net/golang/go-sorting-with-sort-tutorial/
type Programmer struct {
Name string
Age int
}
/* 建立一個符合 sort.interface 的 type */
type byAge []Programmer
func (p byAge) Len() int {
return len(p)
}
func (p byAge) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p byAge) Less(i, j int) bool {
return p[i].Age < p[j].Age
}
func main() {
programmers := []Programmer{
{Name: "Aaron", Age: 30},
{Name: "Bruce", Age: 20},
{Name: "Candy", Age: 50},
{Name: "Derek", Age: 1000},
}
sort.Sort(byAge(programmers))
fmt.Println(programmers)
}
參考
- Go Sorting With the sort Package - Tutorial @ tutorialEdge