Sorting

Sorting is an important part of all programming languages, and golang provides various ways of sorting data.

The golang sort package implements sorting for built-in datatypes and user-defined types. We’ll look at sorting for built-ins first.

package main

import (
  "fmt"
  "sort"
)

func main(){
  ages := []int{23, 12, 25, 32, 19, 11, 13}
  fmt.Println("unsorted ages:", ages)
  sort.Ints(ages) // sorts integers in-place
  fmt.Println("sorted ages: ", ages)
  
  grades := []string{"F", "D", "A", "B", "C", "F", "C"}
  sort.Strings(grades)
  fmt.Println(grades)
}

We can also check if items are already in sorted order by using the IntsAreSorted or StringsAreSorted methods. For example,

ages := []int{23, 12, 25, 32, 19, 11, 13}
ages_is_sorted := sort.IntsAreSorted(ages)
fmt.Println("Sorted: ", ages_is_sorted) // returns false
sort.Ints(ages)
ages_is_sorted := sort.IntsAreSorted(ages)
fmt.Println("Sorted: ", ages_is_sorted) // returns true after sorting

Sorting by Function

In the above section, sorting numerical values will always sort by magnitude, while sorting string values will always sort by lexicological order. However, we may be interested in sorting by some other heuristic function, for example, length of string. We can define our own function as follows:

package main

import (
  "fmt"
  "sort"
)

// we need a corresponding type to sort by custom function in golang
// here we simply create a synonym of the []string type
type by_len []string

// return the len function as a closure
func (val by_len) Len() int {
  return len(val)
}
func (val by_len) Swap(i, j int) {
  val[i], val[j] = val[j], val[i]
}
func (val by_len) Less(i, j int) bool {
  return len(val[i]) < len(val[j])
}

func main() {
  video_games := []string{"Assassin's Creed", "Cyberpunk", "God of War"}
  sort.Sort(by_len(video_games))
  fmt.Println(video_games)
}
// output:
// [Cyberpunk God of War Assassin's Creed]

Len, Less, and Swap are interfaces from the built-in sort package. We apply the interfaces on our custom type so we can use the generic Sort function. Len and Swap will usually be similar across types and Less will hold the actual custom sorting logic. In this case, Less orders the items by ascending order of length.

Last updated