]> Cypherpunks repositories - gostls13.git/commitdiff
sort: add Reverse as a function
authorMiek Gieben <miek@miek.nl>
Fri, 1 Feb 2013 16:44:45 +0000 (08:44 -0800)
committerRuss Cox <rsc@golang.org>
Fri, 1 Feb 2013 16:44:45 +0000 (08:44 -0800)
This updates: https://golang.org/cl/6909059/
Fixes #4511.

R=minux.ma, rsc
CC=golang-dev
https://golang.org/cl/6932054

src/pkg/sort/example_test.go
src/pkg/sort/sort.go
src/pkg/sort/sort_test.go

index f57d02546f79aecc82e788ad2ede8ab01a3e7a66..f7372bec3754faeb0d3eb30fdabb8dad96886920 100644 (file)
@@ -15,3 +15,10 @@ func ExampleInts() {
        fmt.Println(s)
        // Output: [1 2 3 4 5 6]
 }
+
+func ExampleReverse() {
+       s := []int{5, 2, 6, 3, 1, 4} // unsorted
+       sort.Sort(sort.Reverse(sort.IntSlice(s)))
+       fmt.Println(s)
+       // Output: [6 5 4 3 2 1]
+}
index 62a4d55e798477ed6c71d3fb3778bda4f89ab394..3f7a99730c8cef665a0df6e046822ffc61d46eab 100644 (file)
@@ -197,6 +197,22 @@ func Sort(data Interface) {
        quickSort(data, 0, n, maxDepth)
 }
 
+type reverse struct {
+       // This embedded Interface permits Reverse to use the methods of
+       // another Interface implementation.
+       Interface
+}
+
+// Less returns the opposite of the embedded implementation's Less method.
+func (r reverse) Less(i, j int) bool {
+       return r.Interface.Less(j, i)
+}
+
+// Reverse returns the reverse order for data.
+func Reverse(data Interface) Interface {
+       return &reverse{data}
+}
+
 // IsSorted reports whether data is sorted.
 func IsSorted(data Interface) bool {
        n := data.Len()
index ee8a9d0e8499f2f38bf9d10ece6c229f1e0386f9..439a3d5399ed7d7f31c5378a3ede8e96556406a8 100644 (file)
@@ -92,6 +92,23 @@ func TestSortLarge_Random(t *testing.T) {
        }
 }
 
+func TestReverseSortIntSlice(t *testing.T) {
+       data := ints
+       data1 := ints
+       a := IntSlice(data[0:])
+       Sort(a)
+       r := IntSlice(data1[0:])
+       Sort(Reverse(r))
+       for i := 0; i < len(data); i++ {
+               if a[i] != r[len(data)-1-i] {
+                       t.Errorf("reverse sort didn't sort")
+               }
+               if i > len(data)/2 {
+                       break
+               }
+       }
+}
+
 func BenchmarkSortString1K(b *testing.B) {
        b.StopTimer()
        for i := 0; i < b.N; i++ {