Navigation Menu

Skip to content

Commit

Permalink
sort: add Reverse as a function
Browse files Browse the repository at this point in the history
This updates: https://golang.org/cl/6909059/
Fixes #4511.

R=minux.ma, rsc
CC=golang-dev
https://golang.org/cl/6932054
  • Loading branch information
miekg authored and rsc committed Feb 1, 2013
1 parent e515d80 commit d4cfe28
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/pkg/sort/example_test.go
Expand Up @@ -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]
}
16 changes: 16 additions & 0 deletions src/pkg/sort/sort.go
Expand Up @@ -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()
Expand Down
17 changes: 17 additions & 0 deletions src/pkg/sort/sort_test.go
Expand Up @@ -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++ {
Expand Down

0 comments on commit d4cfe28

Please sign in to comment.