version: 1.10

package sort

import "sort"

Overview

Package sort provides primitives for sorting slices and user-defined
collections.


Example:

  1. package sort_test
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type Person struct {
  7. Name string
  8. Age int
  9. }
  10. func (p Person) String() string {
  11. return fmt.Sprintf("%s: %d", p.Name, p.Age)
  12. }
  13. // ByAge implements sort.Interface for []Person based on
  14. // the Age field.
  15. type ByAge []Person
  16. func (a ByAge) Len() int { return len(a) }
  17. func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  18. func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
  19. func Example() {
  20. people := []Person{
  21. {"Bob", 31},
  22. {"John", 42},
  23. {"Michael", 17},
  24. {"Jenny", 26},
  25. }
  26. fmt.Println(people)
  27. // There are two ways to sort a slice. First, one can define
  28. // a set of methods for the slice type, as with ByAge, and
  29. // call sort.Sort. In this first example we use that technique.
  30. sort.Sort(ByAge(people))
  31. fmt.Println(people)
  32. // The other way is to use sort.Slice with a custom Less
  33. // function, which can be provided as a closure. In this
  34. // case no methods are needed. (And if they exist, they
  35. // are ignored.) Here we re-sort in reverse order: compare
  36. // the closure with ByAge.Less.
  37. sort.Slice(people, func(i, j int) bool {
  38. return people[i].Age > people[j].Age
  39. })
  40. fmt.Println(people)
  41. // Output:
  42. // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
  43. // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
  44. // [John: 42 Bob: 31 Jenny: 26 Michael: 17]
  45. }


Example:

  1. package sort_test
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. // A couple of type definitions to make the units clear.
  7. type earthMass float64
  8. type au float64
  9. // A Planet defines the properties of a solar system object.
  10. type Planet struct {
  11. name string
  12. mass earthMass
  13. distance au
  14. }
  15. // By is the type of a "less" function that defines the ordering of its Planet arguments.
  16. type By func(p1, p2 *Planet) bool
  17. // Sort is a method on the function type, By, that sorts the argument slice according to the function.
  18. func (by By) Sort(planets []Planet) {
  19. ps := &planetSorter{
  20. planets: planets,
  21. by: by, // The Sort method's receiver is the function (closure) that defines the sort order.
  22. }
  23. sort.Sort(ps)
  24. }
  25. // planetSorter joins a By function and a slice of Planets to be sorted.
  26. type planetSorter struct {
  27. planets []Planet
  28. by func(p1, p2 *Planet) bool // Closure used in the Less method.
  29. }
  30. // Len is part of sort.Interface.
  31. func (s *planetSorter) Len() int {
  32. return len(s.planets)
  33. }
  34. // Swap is part of sort.Interface.
  35. func (s *planetSorter) Swap(i, j int) {
  36. s.planets[i], s.planets[j] = s.planets[j], s.planets[i]
  37. }
  38. // Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
  39. func (s *planetSorter) Less(i, j int) bool {
  40. return s.by(&s.planets[i], &s.planets[j])
  41. }
  42. var planets = []Planet{
  43. {"Mercury", 0.055, 0.4},
  44. {"Venus", 0.815, 0.7},
  45. {"Earth", 1.0, 1.0},
  46. {"Mars", 0.107, 1.5},
  47. }
  48. // ExampleSortKeys demonstrates a technique for sorting a struct type using programmable sort criteria.
  49. func Example_sortKeys() {
  50. // Closures that order the Planet structure.
  51. name := func(p1, p2 *Planet) bool {
  52. return p1.name < p2.name
  53. }
  54. mass := func(p1, p2 *Planet) bool {
  55. return p1.mass < p2.mass
  56. }
  57. distance := func(p1, p2 *Planet) bool {
  58. return p1.distance < p2.distance
  59. }
  60. decreasingDistance := func(p1, p2 *Planet) bool {
  61. return distance(p2, p1)
  62. }
  63. // Sort the planets by the various criteria.
  64. By(name).Sort(planets)
  65. fmt.Println("By name:", planets)
  66. By(mass).Sort(planets)
  67. fmt.Println("By mass:", planets)
  68. By(distance).Sort(planets)
  69. fmt.Println("By distance:", planets)
  70. By(decreasingDistance).Sort(planets)
  71. fmt.Println("By decreasing distance:", planets)
  72. // Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {Venus 0.815 0.7}]
  73. // By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Earth 1 1}]
  74. // By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars 0.107 1.5}]
  75. // By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.7} {Mercury 0.055 0.4}]
  76. }


Example:

  1. package sort_test
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. // A Change is a record of source code changes, recording user, language, and delta size.
  7. type Change struct {
  8. user string
  9. language string
  10. lines int
  11. }
  12. type lessFunc func(p1, p2 *Change) bool
  13. // multiSorter implements the Sort interface, sorting the changes within.
  14. type multiSorter struct {
  15. changes []Change
  16. less []lessFunc
  17. }
  18. // Sort sorts the argument slice according to the less functions passed to OrderedBy.
  19. func (ms *multiSorter) Sort(changes []Change) {
  20. ms.changes = changes
  21. sort.Sort(ms)
  22. }
  23. // OrderedBy returns a Sorter that sorts using the less functions, in order.
  24. // Call its Sort method to sort the data.
  25. func OrderedBy(less ...lessFunc) *multiSorter {
  26. return &multiSorter{
  27. less: less,
  28. }
  29. }
  30. // Len is part of sort.Interface.
  31. func (ms *multiSorter) Len() int {
  32. return len(ms.changes)
  33. }
  34. // Swap is part of sort.Interface.
  35. func (ms *multiSorter) Swap(i, j int) {
  36. ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
  37. }
  38. // Less is part of sort.Interface. It is implemented by looping along the
  39. // less functions until it finds a comparison that discriminates between
  40. // the two items (one is less than the other). Note that it can call the
  41. // less functions twice per call. We could change the functions to return
  42. // -1, 0, 1 and reduce the number of calls for greater efficiency: an
  43. // exercise for the reader.
  44. func (ms *multiSorter) Less(i, j int) bool {
  45. p, q := &ms.changes[i], &ms.changes[j]
  46. // Try all but the last comparison.
  47. var k int
  48. for k = 0; k < len(ms.less)-1; k++ {
  49. less := ms.less[k]
  50. switch {
  51. case less(p, q):
  52. // p < q, so we have a decision.
  53. return true
  54. case less(q, p):
  55. // p > q, so we have a decision.
  56. return false
  57. }
  58. // p == q; try the next comparison.
  59. }
  60. // All comparisons to here said "equal", so just return whatever
  61. // the final comparison reports.
  62. return ms.less[k](p, q)
  63. }
  64. var changes = []Change{
  65. {"gri", "Go", 100},
  66. {"ken", "C", 150},
  67. {"glenda", "Go", 200},
  68. {"rsc", "Go", 200},
  69. {"r", "Go", 100},
  70. {"ken", "Go", 200},
  71. {"dmr", "C", 100},
  72. {"r", "C", 150},
  73. {"gri", "Smalltalk", 80},
  74. }
  75. // ExampleMultiKeys demonstrates a technique for sorting a struct type using different
  76. // sets of multiple fields in the comparison. We chain together "Less" functions, each of
  77. // which compares a single field.
  78. func Example_sortMultiKeys() {
  79. // Closures that order the Change structure.
  80. user := func(c1, c2 *Change) bool {
  81. return c1.user < c2.user
  82. }
  83. language := func(c1, c2 *Change) bool {
  84. return c1.language < c2.language
  85. }
  86. increasingLines := func(c1, c2 *Change) bool {
  87. return c1.lines < c2.lines
  88. }
  89. decreasingLines := func(c1, c2 *Change) bool {
  90. return c1.lines > c2.lines // Note: > orders downwards.
  91. }
  92. // Simple use: Sort by user.
  93. OrderedBy(user).Sort(changes)
  94. fmt.Println("By user:", changes)
  95. // More examples.
  96. OrderedBy(user, increasingLines).Sort(changes)
  97. fmt.Println("By user,<lines:", changes)
  98. OrderedBy(user, decreasingLines).Sort(changes)
  99. fmt.Println("By user,>lines:", changes)
  100. OrderedBy(language, increasingLines).Sort(changes)
  101. fmt.Println("By language,<lines:", changes)
  102. OrderedBy(language, increasingLines, user).Sort(changes)
  103. fmt.Println("By language,<lines,user:", changes)
  104. // Output:
  105. // By user: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
  106. // By user,<lines: [{dmr C 100} {glenda Go 200} {gri Smalltalk 80} {gri Go 100} {ken C 150} {ken Go 200} {r Go 100} {r C 150} {rsc Go 200}]
  107. // By user,>lines: [{dmr C 100} {glenda Go 200} {gri Go 100} {gri Smalltalk 80} {ken Go 200} {ken C 150} {r C 150} {r Go 100} {rsc Go 200}]
  108. // By language,<lines: [{dmr C 100} {ken C 150} {r C 150} {r Go 100} {gri Go 100} {ken Go 200} {glenda Go 200} {rsc Go 200} {gri Smalltalk 80}]
  109. // By language,<lines,user: [{dmr C 100} {ken C 150} {r C 150} {gri Go 100} {r Go 100} {glenda Go 200} {ken Go 200} {rsc Go 200} {gri Smalltalk 80}]
  110. }


Example:

  1. package sort_test
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type Grams int
  7. func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
  8. type Organ struct {
  9. Name string
  10. Weight Grams
  11. }
  12. type Organs []*Organ
  13. func (s Organs) Len() int { return len(s) }
  14. func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  15. // ByName implements sort.Interface by providing Less and using the Len and
  16. // Swap methods of the embedded Organs value.
  17. type ByName struct{ Organs }
  18. func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
  19. // ByWeight implements sort.Interface by providing Less and using the Len and
  20. // Swap methods of the embedded Organs value.
  21. type ByWeight struct{ Organs }
  22. func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
  23. func Example_sortWrapper() {
  24. s := []*Organ{
  25. {"brain", 1340},
  26. {"heart", 290},
  27. {"liver", 1494},
  28. {"pancreas", 131},
  29. {"prostate", 62},
  30. {"spleen", 162},
  31. }
  32. sort.Sort(ByWeight{s})
  33. fmt.Println("Organs by weight:")
  34. printOrgans(s)
  35. sort.Sort(ByName{s})
  36. fmt.Println("Organs by name:")
  37. printOrgans(s)
  38. // Output:
  39. // Organs by weight:
  40. // prostate (62g)
  41. // pancreas (131g)
  42. // spleen (162g)
  43. // heart (290g)
  44. // brain (1340g)
  45. // liver (1494g)
  46. // Organs by name:
  47. // brain (1340g)
  48. // heart (290g)
  49. // liver (1494g)
  50. // pancreas (131g)
  51. // prostate (62g)
  52. // spleen (162g)
  53. }
  54. func printOrgans(s []*Organ) {
  55. for _, o := range s {
  56. fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
  57. }
  58. }

Index

Examples

Package files

search.go slice.go sort.go zfuncversion.go

func Float64s

  1. func Float64s(a []float64)

Float64s sorts a slice of float64s in increasing order (not-a-number values are
treated as less than other values).


Example:

  1. s := []float64{5.2, -1.3, 0.7, -3.8, 2.6} // unsorted
  2. sort.Float64s(s)
  3. fmt.Println(s)
  4. s = []float64{math.Inf(1), math.NaN(), math.Inf(-1), 0.0} // unsorted
  5. sort.Float64s(s)
  6. fmt.Println(s)
  7. // Output: [-3.8 -1.3 0.7 2.6 5.2]
  8. // [NaN -Inf 0 +Inf]

func Float64sAreSorted

  1. func Float64sAreSorted(a []float64) bool

Float64sAreSorted tests whether a slice of float64s is sorted in increasing
order (not-a-number values are treated as less than other values).


Example:

  1. s := []float64{0.7, 1.3, 2.6, 3.8, 5.2} // sorted ascending
  2. fmt.Println(sort.Float64sAreSorted(s))
  3. s = []float64{5.2, 3.8, 2.6, 1.3, 0.7} // sorted descending
  4. fmt.Println(sort.Float64sAreSorted(s))
  5. s = []float64{5.2, 1.3, 0.7, 3.8, 2.6} // unsorted
  6. fmt.Println(sort.Float64sAreSorted(s))
  7. // Output: true
  8. // false
  9. // false

func Ints

  1. func Ints(a []int)

Ints sorts a slice of ints in increasing order.


Example:

  1. s := []int{5, 2, 6, 3, 1, 4} // unsorted
  2. sort.Ints(s)
  3. fmt.Println(s)
  4. // Output: [1 2 3 4 5 6]

func IntsAreSorted

  1. func IntsAreSorted(a []int) bool

IntsAreSorted tests whether a slice of ints is sorted in increasing order.


Example:

  1. s := []int{1, 2, 3, 4, 5, 6} // sorted ascending
  2. fmt.Println(sort.IntsAreSorted(s))
  3. s = []int{6, 5, 4, 3, 2, 1} // sorted descending
  4. fmt.Println(sort.IntsAreSorted(s))
  5. s = []int{3, 2, 4, 1, 5} // unsorted
  6. fmt.Println(sort.IntsAreSorted(s))
  7. // Output: true
  8. // false
  9. // false

func IsSorted

  1. func IsSorted(data Interface) bool

IsSorted reports whether data is sorted.

  1. func Search(n int, f func(int) bool) int

Search uses binary search to find and return the smallest index i in [0, n) at
which f(i) is true, assuming that on the range [0, n), f(i) == true implies
f(i+1) == true. That is, Search requires that f is false for some (possibly
empty) prefix of the input range [0, n) and then true for the (possibly empty)
remainder; Search returns the first true index. If there is no such index,
Search returns n. (Note that the “not found” return value is not -1 as in, for
instance, strings.Index.) Search calls f(i) only for i in the range [0, n).

A common use of Search is to find the index i for a value x in a sorted,
indexable data structure such as an array or slice. In this case, the argument
f, typically a closure, captures the value to be searched for, and how the data
structure is indexed and ordered.

For instance, given a slice data sorted in ascending order, the call
Search(len(data), func(i int) bool { return data[i] >= 23 }) returns the
smallest index i such that data[i] >= 23. If the caller wants to find whether 23
is in the slice, it must test data[i] == 23 separately.

Searching data sorted in descending order would use the <= operator instead of
the >= operator.

To complete the example above, the following code tries to find the value x in
an integer slice data sorted in ascending order:

  1. x := 23
  2. i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
  3. if i < len(data) && data[i] == x {
  4. // x is present at data[i]
  5. } else {
  6. // x is not present in data,
  7. // but i is the index where it would be inserted.
  8. }

As a more whimsical example, this program guesses your number:

  1. func GuessingGame() {
  2. var s string
  3. fmt.Printf("Pick an integer from 0 to 100.\n")
  4. answer := sort.Search(100, func(i int) bool {
  5. fmt.Printf("Is your number <= %d? ", i)
  6. fmt.Scanf("%s", &s)
  7. return s != "" && s[0] == 'y'
  8. })
  9. fmt.Printf("Your number is %d.\n", answer)
  10. }


Example:

  1. a := []int{1, 3, 6, 10, 15, 21, 28, 36, 45, 55}
  2. x := 6
  3. i := sort.Search(len(a), func(i int) bool { return a[i] >= x })
  4. if i < len(a) && a[i] == x {
  5. fmt.Printf("found %d at index %d in %v\n", x, i, a)
  6. } else {
  7. fmt.Printf("%d not found in %v\n", x, a)
  8. }
  9. // Output:
  10. // found 6 at index 2 in [1 3 6 10 15 21 28 36 45 55]


Example:

  1. a := []int{55, 45, 36, 28, 21, 15, 10, 6, 3, 1}
  2. x := 6
  3. i := sort.Search(len(a), func(i int) bool { return a[i] <= x })
  4. if i < len(a) && a[i] == x {
  5. fmt.Printf("found %d at index %d in %v\n", x, i, a)
  6. } else {
  7. fmt.Printf("%d not found in %v\n", x, a)
  8. }
  9. // Output:
  10. // found 6 at index 7 in [55 45 36 28 21 15 10 6 3 1]

func SearchFloat64s

  1. func SearchFloat64s(a []float64, x float64) int

SearchFloat64s searches for x in a sorted slice of float64s and returns the
index as specified by Search. The return value is the index to insert x if x is
not present (it could be len(a)). The slice must be sorted in ascending order.

func SearchInts

  1. func SearchInts(a []int, x int) int

SearchInts searches for x in a sorted slice of ints and returns the index as
specified by Search. The return value is the index to insert x if x is not
present (it could be len(a)). The slice must be sorted in ascending order.

func SearchStrings

  1. func SearchStrings(a []string, x string) int

SearchStrings searches for x in a sorted slice of strings and returns the index
as specified by Search. The return value is the index to insert x if x is not
present (it could be len(a)). The slice must be sorted in ascending order.

func Slice

  1. func Slice(slice interface{}, less func(i, j int) bool)

Slice sorts the provided slice given the provided less function.

The sort is not guaranteed to be stable. For a stable sort, use SliceStable.

The function panics if the provided interface is not a slice.


Example:

  1. people := []struct {
  2. Name string
  3. Age int
  4. }{
  5. {"Gopher", 7},
  6. {"Alice", 55},
  7. {"Vera", 24},
  8. {"Bob", 75},
  9. }
  10. sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
  11. fmt.Println("By name:", people)
  12. sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
  13. fmt.Println("By age:", people)
  14. // Output: By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
  15. // By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]

func SliceIsSorted

  1. func SliceIsSorted(slice interface{}, less func(i, j int) bool) bool

SliceIsSorted tests whether a slice is sorted.

The function panics if the provided interface is not a slice.

func SliceStable

  1. func SliceStable(slice interface{}, less func(i, j int) bool)

SliceStable sorts the provided slice given the provided less function while
keeping the original order of equal elements.

The function panics if the provided interface is not a slice.


Example:

  1. people := []struct {
  2. Name string
  3. Age int
  4. }{
  5. {"Alice", 25},
  6. {"Elizabeth", 75},
  7. {"Alice", 75},
  8. {"Bob", 75},
  9. {"Alice", 75},
  10. {"Bob", 25},
  11. {"Colin", 25},
  12. {"Elizabeth", 25},
  13. }
  14. // Sort by name, preserving original order
  15. sort.SliceStable(people, func(i, j int) bool { return people[i].Name < people[j].Name })
  16. fmt.Println("By name:", people)
  17. // Sort by age preserving name order
  18. sort.SliceStable(people, func(i, j int) bool { return people[i].Age < people[j].Age })
  19. fmt.Println("By age,name:", people)
  20. // Output: By name: [{Alice 25} {Alice 75} {Alice 75} {Bob 75} {Bob 25} {Colin 25} {Elizabeth 75} {Elizabeth 25}]
  21. // By age,name: [{Alice 25} {Bob 25} {Colin 25} {Elizabeth 25} {Alice 75} {Alice 75} {Bob 75} {Elizabeth 75}]

func Sort

  1. func Sort(data Interface)

Sort sorts data. It makes one call to data.Len to determine n, and O(n*log(n))
calls to data.Less and data.Swap. The sort is not guaranteed to be stable.

func Stable

  1. func Stable(data Interface)

Stable sorts data while keeping the original order of equal elements.

It makes one call to data.Len to determine n, O(nlog(n)) calls to data.Less and
O(n
log(n)*log(n)) calls to data.Swap.

func Strings

  1. func Strings(a []string)

Strings sorts a slice of strings in increasing order.


Example:

  1. s := []string{"Go", "Bravo", "Gopher", "Alpha", "Grin", "Delta"}
  2. sort.Strings(s)
  3. fmt.Println(s)
  4. // Output: [Alpha Bravo Delta Go Gopher Grin]

func StringsAreSorted

  1. func StringsAreSorted(a []string) bool

StringsAreSorted tests whether a slice of strings is sorted in increasing order.

type Float64Slice

  1. type Float64Slice []float64

Float64Slice attaches the methods of Interface to []float64, sorting in
increasing order (not-a-number values are treated as less than other values).

func (Float64Slice) Len

  1. func (p Float64Slice) Len() int

func (Float64Slice) Less

  1. func (p Float64Slice) Less(i, j int) bool

func (Float64Slice) Search

  1. func (p Float64Slice) Search(x float64) int

Search returns the result of applying SearchFloat64s to the receiver and x.

func (Float64Slice) Sort

  1. func (p Float64Slice) Sort()

Sort is a convenience method.

func (Float64Slice) Swap

  1. func (p Float64Slice) Swap(i, j int)

type IntSlice

  1. type IntSlice []int

IntSlice attaches the methods of Interface to []int, sorting in increasing
order.

func (IntSlice) Len

  1. func (p IntSlice) Len() int

func (IntSlice) Less

  1. func (p IntSlice) Less(i, j int) bool

func (IntSlice) Search

  1. func (p IntSlice) Search(x int) int

Search returns the result of applying SearchInts to the receiver and x.

func (IntSlice) Sort

  1. func (p IntSlice) Sort()

Sort is a convenience method.

func (IntSlice) Swap

  1. func (p IntSlice) Swap(i, j int)

type Interface

  1. type Interface interface {
  2. // Len is the number of elements in the collection.
  3. Len() int
  4. // Less reports whether the element with
  5. // index i should sort before the element with index j.
  6. Less(i, j int) bool
  7. // Swap swaps the elements with indexes i and j.
  8. Swap(i, j int)
  9. }

A type, typically a collection, that satisfies sort.Interface can be sorted by
the routines in this package. The methods require that the elements of the
collection be enumerated by an integer index.

func Reverse

  1. func Reverse(data Interface) Interface

Reverse returns the reverse order for data.


Example:

  1. s := []int{5, 2, 6, 3, 1, 4} // unsorted
  2. sort.Sort(sort.Reverse(sort.IntSlice(s)))
  3. fmt.Println(s)
  4. // Output: [6 5 4 3 2 1]

type StringSlice

  1. type StringSlice []string

StringSlice attaches the methods of Interface to []string, sorting in increasing
order.

func (StringSlice) Len

  1. func (p StringSlice) Len() int

func (StringSlice) Less

  1. func (p StringSlice) Less(i, j int) bool

func (StringSlice) Search

  1. func (p StringSlice) Search(x string) int

Search returns the result of applying SearchStrings to the receiver and x.

func (StringSlice) Sort

  1. func (p StringSlice) Sort()

Sort is a convenience method.

func (StringSlice) Swap

  1. func (p StringSlice) Swap(i, j int)