sortmain.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // This package gives an example of how to use a custom package with interfaces
  5. package main
  6. import (
  7. "fmt"
  8. "./sort"
  9. )
  10. // sorting of slice of integers
  11. func ints() {
  12. data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
  13. a := sort.IntArray(data) //conversion to type IntArray
  14. sort.Sort(a)
  15. if !sort.IsSorted(a) {
  16. panic("fail")
  17. }
  18. fmt.Printf("The sorted array is: %v\n", a)
  19. }
  20. // sorting of slice of strings
  21. func strings() {
  22. data := []string{"monday", "friday", "tuesday", "wednesday", "sunday","thursday", "", "saturday"}
  23. a := sort.StringArray(data)
  24. sort.Sort(a)
  25. if !sort.IsSorted(a) {
  26. panic("fail")
  27. }
  28. fmt.Printf("The sorted array is: %v\n", a)
  29. }
  30. // a type which describes a day of the week
  31. type day struct {
  32. num int
  33. shortName string
  34. longName string
  35. }
  36. type dayArray struct {
  37. data []*day
  38. }
  39. func (p *dayArray) Len() int { return len(p.data) }
  40. func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num }
  41. func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] }
  42. // sorting of custom type day
  43. func days() {
  44. Sunday := day{0, "SUN", "Sunday"}
  45. Monday := day{1, "MON", "Monday"}
  46. Tuesday := day{2, "TUE", "Tuesday"}
  47. Wednesday := day{3, "WED", "Wednesday"}
  48. Thursday := day{4, "THU", "Thursday"}
  49. Friday := day{5, "FRI", "Friday"}
  50. Saturday := day{6, "SAT", "Saturday"}
  51. data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday}
  52. a := dayArray{data}
  53. sort.Sort(&a)
  54. if !sort.IsSorted(&a) {
  55. panic("fail")
  56. }
  57. for _, d := range data {
  58. fmt.Printf("%s ", d.longName)
  59. }
  60. fmt.Printf("\n")
  61. }
  62. func main() {
  63. ints()
  64. strings()
  65. days()
  66. }
  67. /* Output:
  68. The sorted array is: [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845]
  69. The sorted array is: [ friday monday saturday sunday thursday tuesday wednesday]
  70. Sunday Monday Tuesday Wednesday Thursday Friday Saturday
  71. */