Source file
doc/progs/eff_sequence.go
1
2
3
4
5 package main
6
7 import (
8 "fmt"
9 "sort"
10 )
11
12 func main() {
13 seq := Sequence{6, 2, -1, 44, 16}
14 sort.Sort(seq)
15 fmt.Println(seq)
16 }
17
18 type Sequence []int
19
20
21 func (s Sequence) Len() int {
22 return len(s)
23 }
24 func (s Sequence) Less(i, j int) bool {
25 return s[i] < s[j]
26 }
27 func (s Sequence) Swap(i, j int) {
28 s[i], s[j] = s[j], s[i]
29 }
30
31
32 func (s Sequence) Copy() Sequence {
33 copy := make(Sequence, 0, len(s))
34 return append(copy, s...)
35 }
36
37
38 func (s Sequence) String() string {
39 s = s.Copy()
40 sort.Sort(s)
41 str := "["
42 for i, elem := range s {
43 if i > 0 {
44 str += " "
45 }
46 str += fmt.Sprint(elem)
47 }
48 return str + "]"
49 }
50
View as plain text