-
-
Notifications
You must be signed in to change notification settings - Fork 519
/
Copy patharray_sort.go
60 lines (48 loc) · 992 Bytes
/
array_sort.go
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type PersonCollection []Person
func (pc PersonCollection) Len() int {
return len(pc)
}
func (pc PersonCollection) Swap(i, j int) {
pc[i], pc[j] = pc[j], pc[i]
}
func (pc PersonCollection) Less(i, j int) bool {
// asc
return pc[i].Age < pc[j].Age
}
func main() {
intList := []int{1, 3, 5, 9, 4, 2, 0}
// asc
sort.Ints(intList)
fmt.Println(intList)
// desc
sort.Sort(sort.Reverse(sort.IntSlice(intList)))
fmt.Println(intList)
stringList := []string{"a", "d", "z", "b", "c", "y"}
// asc
sort.Strings(stringList)
fmt.Println(stringList)
// desc
sort.Sort(sort.Reverse(sort.StringSlice(stringList)))
fmt.Println(stringList)
collection := []Person{
{"Li L", 8},
{"Json C", 3},
{"Zack W", 15},
{"Yi M", 2},
}
// asc
sort.Sort(PersonCollection(collection))
fmt.Println(collection)
// desc
sort.Sort(sort.Reverse(PersonCollection(collection)))
fmt.Println(collection)
}