Source file
src/sort/example_test.go
Documentation: sort
1
2
3
4
5 package sort_test
6
7 import (
8 "fmt"
9 "math"
10 "sort"
11 )
12
13 func ExampleInts() {
14 s := []int{5, 2, 6, 3, 1, 4}
15 sort.Ints(s)
16 fmt.Println(s)
17
18 }
19
20 func ExampleIntsAreSorted() {
21 s := []int{1, 2, 3, 4, 5, 6}
22 fmt.Println(sort.IntsAreSorted(s))
23
24 s = []int{6, 5, 4, 3, 2, 1}
25 fmt.Println(sort.IntsAreSorted(s))
26
27 s = []int{3, 2, 4, 1, 5}
28 fmt.Println(sort.IntsAreSorted(s))
29
30
31
32
33 }
34
35 func ExampleFloat64s() {
36 s := []float64{5.2, -1.3, 0.7, -3.8, 2.6}
37 sort.Float64s(s)
38 fmt.Println(s)
39
40 s = []float64{math.Inf(1), math.NaN(), math.Inf(-1), 0.0}
41 sort.Float64s(s)
42 fmt.Println(s)
43
44
45
46 }
47
48 func ExampleFloat64sAreSorted() {
49 s := []float64{0.7, 1.3, 2.6, 3.8, 5.2}
50 fmt.Println(sort.Float64sAreSorted(s))
51
52 s = []float64{5.2, 3.8, 2.6, 1.3, 0.7}
53 fmt.Println(sort.Float64sAreSorted(s))
54
55 s = []float64{5.2, 1.3, 0.7, 3.8, 2.6}
56 fmt.Println(sort.Float64sAreSorted(s))
57
58
59
60
61 }
62
63 func ExampleReverse() {
64 s := []int{5, 2, 6, 3, 1, 4}
65 sort.Sort(sort.Reverse(sort.IntSlice(s)))
66 fmt.Println(s)
67
68 }
69
70 func ExampleSlice() {
71 people := []struct {
72 Name string
73 Age int
74 }{
75 {"Gopher", 7},
76 {"Alice", 55},
77 {"Vera", 24},
78 {"Bob", 75},
79 }
80 sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
81 fmt.Println("By name:", people)
82
83 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
84 fmt.Println("By age:", people)
85
86
87 }
88
89 func ExampleSliceStable() {
90
91 people := []struct {
92 Name string
93 Age int
94 }{
95 {"Alice", 25},
96 {"Elizabeth", 75},
97 {"Alice", 75},
98 {"Bob", 75},
99 {"Alice", 75},
100 {"Bob", 25},
101 {"Colin", 25},
102 {"Elizabeth", 25},
103 }
104
105
106 sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
107 fmt.Println("By name:", people)
108
109
110 sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
111 fmt.Println("By age,name:", people)
112
113
114
115 }
116
117 func ExampleStrings() {
118 s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
119 sort.Strings(s)
120 fmt.Println(s)
121
122 }
123
View as plain text