sortutil.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. /*
  10. Package sortutil contains common sorting definitions and utilities for sorting data.
  11. */
  12. package sortutil
  13. import (
  14. "fmt"
  15. "sort"
  16. )
  17. /*
  18. Int64Slice is a special type implementing the sort interface for int64
  19. */
  20. type Int64Slice []int64
  21. func (p Int64Slice) Len() int { return len(p) }
  22. func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] }
  23. func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  24. /*
  25. Int64s sorts a slice of int64s in increasing order.
  26. */
  27. func Int64s(a []int64) { sort.Sort(Int64Slice(a)) }
  28. /*
  29. UInt64Slice is a special type implementing the sort interface for uint64
  30. */
  31. type UInt64Slice []uint64
  32. func (p UInt64Slice) Len() int { return len(p) }
  33. func (p UInt64Slice) Less(i, j int) bool { return p[i] < p[j] }
  34. func (p UInt64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  35. /*
  36. UInt64s sorts a slice of uint64s in increasing order.
  37. */
  38. func UInt64s(a []uint64) { sort.Sort(UInt64Slice(a)) }
  39. /*
  40. AbstractSlice is a special type implementing the sort interface for interface{}
  41. (Sorting is by string value)
  42. */
  43. type AbstractSlice []interface{}
  44. func (p AbstractSlice) Len() int { return len(p) }
  45. func (p AbstractSlice) Less(i, j int) bool { return fmt.Sprint(p[i]) < fmt.Sprint(p[j]) }
  46. func (p AbstractSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  47. /*
  48. InterfaceStrings sorts a slice of interface{} in increasing order by their string
  49. values.
  50. */
  51. func InterfaceStrings(a []interface{}) { sort.Sort(AbstractSlice(a)) }