1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 s := []int{5, 2, 6, 3, 1, 4} // unsorted
17 // Output: [1 2 3 4 5 6]
20 func ExampleIntsAreSorted() {
21 s := []int{1, 2, 3, 4, 5, 6} // sorted ascending
22 fmt.Println(sort.IntsAreSorted(s))
24 s = []int{6, 5, 4, 3, 2, 1} // sorted descending
25 fmt.Println(sort.IntsAreSorted(s))
27 s = []int{3, 2, 4, 1, 5} // unsorted
28 fmt.Println(sort.IntsAreSorted(s))
35 func ExampleFloat64s() {
36 s := []float64{5.2, -1.3, 0.7, -3.8, 2.6} // unsorted
40 s = []float64{math.Inf(1), math.NaN(), math.Inf(-1), 0.0} // unsorted
44 // Output: [-3.8 -1.3 0.7 2.6 5.2]
48 func ExampleFloat64sAreSorted() {
49 s := []float64{0.7, 1.3, 2.6, 3.8, 5.2} // sorted ascending
50 fmt.Println(sort.Float64sAreSorted(s))
52 s = []float64{5.2, 3.8, 2.6, 1.3, 0.7} // sorted descending
53 fmt.Println(sort.Float64sAreSorted(s))
55 s = []float64{5.2, 1.3, 0.7, 3.8, 2.6} // unsorted
56 fmt.Println(sort.Float64sAreSorted(s))
63 func ExampleReverse() {
64 s := []int{5, 2, 6, 3, 1, 4} // unsorted
65 sort.Sort(sort.Reverse(sort.IntSlice(s)))
67 // Output: [6 5 4 3 2 1]
80 sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
81 fmt.Println("By name:", people)
83 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
84 fmt.Println("By age:", people)
85 // Output: By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
86 // By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
89 func ExampleSliceStable() {
105 // Sort by name, preserving original order
106 sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
107 fmt.Println("By name:", people)
109 // Sort by age preserving name order
110 sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
111 fmt.Println("By age,name:", people)
113 // Output: By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}]
114 // By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}]
117 func ExampleStrings() {
118 s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
121 // Output: [Alpha Bravo Delta Go Gopher Grin]