Algorithms#
The standard library covers most everyday algorithmic needs. Reach for
sort, container/heap, and slices before rolling your own.
Sorting#
import "sort"
xs := []int{5, 1, 4, 2, 3}
sort.Ints(xs) // ascending
names := []string{"b", "a"}
sort.Strings(names)
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
Since Go 1.21, generic helpers live in the slices package:
import "slices"
slices.Sort(xs)
slices.SortFunc(people, func(a, b Person) int { return a.Age - b.Age })
Search#
import "sort"
i := sort.SearchInts(xs, target)
if i < len(xs) && xs[i] == target { /* found */ }
Recursion#
func fact(n int) int {
if n <= 1 {
return 1
}
return n * fact(n-1)
}
Linked List#
type Node struct {
Value int
Next *Node
}
func push(head *Node, v int) *Node {
return &Node{Value: v, Next: head}
}
Concurrent Map-Reduce#
func sum(xs []int) int {
const workers = 4
chunks := make(chan []int)
results := make(chan int)
go func() {
defer close(chunks)
size := (len(xs) + workers - 1) / workers
for i := 0; i < len(xs); i += size {
end := i + size
if end > len(xs) {
end = len(xs)
}
chunks <- xs[i:end]
}
}()
for i := 0; i < workers; i++ {
go func() {
s := 0
for c := range chunks {
for _, v := range c {
s += v
}
}
results <- s
}()
}
total := 0
for i := 0; i < workers; i++ {
total += <-results
}
return total
}