Go Cheatsheet - Sort

·

2 min read

Sort

Sort Ints

ints := []int{3, 1, 4, 5, 2}
sort.Ints(ints)
// [1 2 3 4 5]

Sort String

strs := []string{"bob", "clair", "alice"}
sort.Strings(strs)
// [alice bob clair]

Sort in Reverse Order

ints := []int{3, 1, 4, 5, 2}
sort.Sort(sort.Reverse(sort.IntSlice(ints)))
// [5 4 3 2 1]

Sort with Custom Compare Function

people := []map[string]interface{}{
    {"name": "bob", "age": 25},
    {"name": "alice", "age": 22},
    {"name": "elon", "age": 21},
    {"name": "david", "age": 24},
    {"name": "frank", "age": 21},
    {"name": "clair", "age": 21},
}

sort.Slice(people, func(i, j int) bool {
    return people[i]["age"].(int) > people[j]["age"].(int)
})
fmt.Println("Sorted People", people)
// [map[age:25 name:bob] map[age:24 name:david] map[age:22 name:alice] map[age:21 name:elon] map[age:21 name:frank] map[age:21 name:clair]]

Stable sort: sort.SliceStable, it will keep equal elements in their original order.

Sort with Sort Interface

type peopleByAge []map[string]interface{}

func (a peopleByAge) Len() int {
    return len(a)
}

func (a peopleByAge) Swap(i, j int) {
    a[i], a[j] = a[j], a[i]
}

func (a peopleByAge) Less(i, j int) bool {
    return a[i]["age"].(int) < a[j]["age"].(int)
}

people := []map[string]interface{}{
    {"name": "bob", "age": 25},
    {"name": "alice", "age": 22},
    {"name": "elon", "age": 21},
    {"name": "david", "age": 24},
    {"name": "frank", "age": 21},
    {"name": "clair", "age": 21},
}

sort.Sort(peopleByAge(people))
fmt.Println("Sorted People", people)
// [map[age:21 name:elon] map[age:21 name:frank] map[age:21 name:clair] map[age:22 name:alice] map[age:24 name:david] map[age:25 name:bob]]

Stable sort: sort.Stable, it will keep equal elements in their original order.

This sort with "Sort Interface" method is preferred compare to the "compare function" above, since the "compare function" method will use reflect which might slow down your sort.