aboutsummaryrefslogtreecommitdiff
path: root/src/sort
diff options
context:
space:
mode:
authorKenny Grant <kennygrant@gmail.com>2017-02-18 16:56:45 +0000
committerBrad Fitzpatrick <bradfitz@golang.org>2017-02-22 21:23:12 +0000
commit8321be63396363cd18e9d23b4b05bcb3e5791fa7 (patch)
tree40ca6109c674c33b0629c64810ee7eb068dc8fc4 /src/sort
parentc12cd31a3326e6b2119525cd07cebc6d6e1b52ee (diff)
downloadgo-8321be63396363cd18e9d23b4b05bcb3e5791fa7.tar.gz
go-8321be63396363cd18e9d23b4b05bcb3e5791fa7.zip
sort: new example: Sorting slices with sort.SliceStable
ExampleSliceStable echoes the sort.Slice example, to demonstrate sorting on two fields together preserving order between sorts. Change-Id: I8afc20c0203991bfd57260431eda73913c165355 Reviewed-on: https://go-review.googlesource.com/37196 Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org> Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org> TryBot-Result: Gobot Gobot <gobot@golang.org>
Diffstat (limited to 'src/sort')
-rw-r--r--src/sort/example_test.go28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/sort/example_test.go b/src/sort/example_test.go
index 980c0d0368..89ebe790c1 100644
--- a/src/sort/example_test.go
+++ b/src/sort/example_test.go
@@ -41,3 +41,31 @@ func ExampleSlice() {
// Output: By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
// By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]
}
+
+func ExampleSliceStable() {
+
+ people := []struct {
+ Name string
+ Age int
+ }{
+ {"Alice", 25},
+ {"Elizabeth", 75},
+ {"Alice", 75},
+ {"Bob", 75},
+ {"Alice", 75},
+ {"Bob", 25},
+ {"Colin", 25},
+ {"Elizabeth", 25},
+ }
+
+ // Sort by name, preserving original order
+ sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
+ fmt.Println("By name:", people)
+
+ // Sort by age preserving name order
+ sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
+ fmt.Println("By age,name:", people)
+
+ // Output: By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}]
+ // By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}]
+}