eff_sequence.go 995 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2009 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. package main
  5. import (
  6. "fmt"
  7. "sort"
  8. )
  9. func main() {
  10. seq := Sequence{6, 2, -1, 44, 16}
  11. sort.Sort(seq)
  12. fmt.Println(seq)
  13. }
  14. type Sequence []int
  15. // Methods required by sort.Interface.
  16. func (s Sequence) Len() int {
  17. return len(s)
  18. }
  19. func (s Sequence) Less(i, j int) bool {
  20. return s[i] < s[j]
  21. }
  22. func (s Sequence) Swap(i, j int) {
  23. s[i], s[j] = s[j], s[i]
  24. }
  25. // Copy returns a copy of the Sequence.
  26. func (s Sequence) Copy() Sequence {
  27. copy := make(Sequence, 0, len(s))
  28. return append(copy, s...)
  29. }
  30. // Method for printing - sorts the elements before printing.
  31. func (s Sequence) String() string {
  32. s = s.Copy() // Make a copy; don't overwrite argument.
  33. sort.Sort(s)
  34. str := "["
  35. for i, elem := range s { // Loop is O(N²); will fix that in next example.
  36. if i > 0 {
  37. str += " "
  38. }
  39. str += fmt.Sprint(elem)
  40. }
  41. return str + "]"
  42. }