github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/sort/example_test.go (about) 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. 4 5 package sort_test 6 7 import ( 8 "fmt" 9 "sort" 10 ) 11 12 func ExampleInts() { 13 s := []int{5, 2, 6, 3, 1, 4} // unsorted 14 sort.Ints(s) 15 fmt.Println(s) 16 // Output: [1 2 3 4 5 6] 17 } 18 19 func ExampleReverse() { 20 s := []int{5, 2, 6, 3, 1, 4} // unsorted 21 sort.Sort(sort.Reverse(sort.IntSlice(s))) 22 fmt.Println(s) 23 // Output: [6 5 4 3 2 1] 24 } 25 26 func ExampleSlice() { 27 people := []struct { 28 Name string 29 Age int 30 }{ 31 {"Gopher", 7}, 32 {"Alice", 55}, 33 {"Vera", 24}, 34 {"Bob", 75}, 35 } 36 sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name }) 37 fmt.Println("By name:", people) 38 39 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) 40 fmt.Println("By age:", people) 41 // Output: By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}] 42 // By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}] 43 } 44 45 func ExampleSliceStable() { 46 47 people := []struct { 48 Name string 49 Age int 50 }{ 51 {"Alice", 25}, 52 {"Elizabeth", 75}, 53 {"Alice", 75}, 54 {"Bob", 75}, 55 {"Alice", 75}, 56 {"Bob", 25}, 57 {"Colin", 25}, 58 {"Elizabeth", 25}, 59 } 60 61 // Sort by name, preserving original order 62 sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name }) 63 fmt.Println("By name:", people) 64 65 // Sort by age preserving name order 66 sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age }) 67 fmt.Println("By age,name:", people) 68 69 // Output: By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}] 70 // By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}] 71 }