sorting by functions

sorting by functions

原文:https://gobyexample.com/sorting-by-functions

存在修改

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
	"fmt"
	"sort"
)

type byLength []string

func (s byLength) Len() int {
	return len(s)
}
func (s byLength) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
	return len(s[i]) < len(s[j])
}

func main() {
	fruits := []string{"peach", "banana", "kiwi", "pear", "apple"}
	sort.Sort(byLength(fruits))
	fmt.Printf("%v\n", fruits)

	sort.Stable(byLength(fruits))
	fmt.Printf("%v\n", fruits)

}
最后修改 March 10, 2024: 更新 (ddf4687)