man go/sorting
How Go sorts: pdqsort in the slices package
Go has two sorting APIs. The sort package is from Go 1 and works on indexes
or an interface; the generic slices package arrived in Go 1.21. A typical
job, ranking keys by a score, looks like this in each:
sort.Slice(keys, func(i, j int) bool { return score[keys[i]] > score[keys[j]] })
slices.SortFunc(keys, func(a, b string) int { return cmp.Compare(score[b], score[a]) })
Which algorithm runs, is it stable, and is the generic one faster? This post
reads the go1.27.4 source of slices and sort and measures them on an Apple
M2 Pro. Every number below comes from that source, the release notes, or a
program I ran.
The short version
Both packages have run pattern-defeating quicksort (pdqsort) since Go 1.19. It is a quicksort that uses insertion sort for ranges of 12 or fewer elements, picks pivots carefully, notices input that is already sorted, and falls back to heapsort when pivots keep coming out bad, so the worst case stays O(n log n). It is not stable. The stable sorts use insertion sort on blocks of 20 and then merge the blocks in place.
One template, four sorts
The sorting code exists once, as a template in
sort/gen_sort_variants.go,
and go generate writes four copies in the standard library (two more
variants are for golang.org/x/exp):
variant file used by
interface sort/zsortinterface.go sort.Sort, sort.Stable
func sort/zsortfunc.go sort.Slice, sort.SliceStable
generic_ordered slices/zsortordered.go slices.Sort
generic_func slices/zsortanyfunc.go slices.SortFunc, slices.SortStableFunc
The difference is only in how two elements are compared and swapped.
sort.Sort calls Less and Swap through an interface. sort.Slice takes
the slice as any, builds a swap function with reflectlite.Swapper, and
calls your less(i, j) on indexes
(slice.go L24-L30).
slices.SortFunc is generic: it swaps elements directly and calls
cmp(a, b) on values. slices.Sort needs no function at all and compares
with < through cmp.Less
(zsortordered.go L12-L18).
Since Go 1.22, sort.Ints, sort.Float64s and sort.Strings simply call
slices.Sort
(sort.go L169-L181).
Inside pdqsort
Everything below is in
pdqsortCmpFunc.
The caller passes a limit of bits.Len(n), the bit length of the slice’s
length
(sort.go L30-L33).
Then each round does this:
loop over data[a:b]:
length <= 12 -> insertion sort, done
limit == 0 -> heapsort, done
last split unbalanced -> scatter 3 elements, limit--
choose pivot (+ a hint: increasing / decreasing / unknown)
hint decreasing -> reverse the range, hint becomes increasing
balanced, partitioned, increasing
-> partial insertion sort; if it finishes, done
pivot equals the element just before the range
-> put all copies of the pivot together, skip them
partition around the pivot
recurse into the smaller side, loop on the larger one
Pivots. Below 8 elements the pivot is the middle one. From 8 it is the median of three elements at a quarter, half and three quarters. From 50 it is Tukey’s ninther: the median of three medians of three neighbouring elements (choosePivotCmpFunc, L256-L295). Choosing the pivot also counts swaps. No swaps means the samples were already in order, the “increasing” hint; 12 swaps, the maximum, means they were in reverse, and the whole range is reversed before going on.
Sorted input. With the increasing hint, the partial insertion sort walks the range and allows at most 5 out-of-order pairs to be fixed (L194-L236). If it reaches the end, the range was sorted and the work is done.
Bad pivots. A split counts as unbalanced when the smaller side has less
than an eighth of the elements. After one, the next round swaps three
elements near the middle with pseudo-random positions
(breakPatternsCmpFunc, L238-L254)
and uses up one unit of limit. When limit reaches 0 the range is
heapsorted.
Many duplicates. If the pivot is not greater than the element just left of the range, which an earlier partition already placed, then everything equal to the pivot is gathered at once and skipped (partitionEqualCmpFunc, L171-L192).
Counting comparisons
I counted the comparisons slices.SortFunc makes on a million ints:
package main
import (
"cmp"
"fmt"
"math/rand/v2"
"slices"
)
func comparisons(xs []int) int {
n := 0
slices.SortFunc(slices.Clone(xs), func(a, b int) int {
n++
return cmp.Compare(a, b)
})
return n
}
func main() {
const n = 1_000_000
r := rand.New(rand.NewPCG(1, 2))
random := make([]int, n)
for i := range random {
random[i] = r.IntN(1 << 30)
}
sorted := slices.Sorted(slices.Values(random))
reversed := slices.Clone(sorted)
slices.Reverse(reversed)
equal := make([]int, n)
fmt.Println("random: ", comparisons(random))
fmt.Println("sorted: ", comparisons(sorted))
fmt.Println("reversed:", comparisons(reversed))
fmt.Println("equal: ", comparisons(equal))
}
$ go run compares.go
random: 21177691
sorted: 1000011
reversed: 1000011
equal: 1000011
Random input costs about 21.2 million comparisons, close to n·log₂n (19.9 million). The other three cost exactly n + 11. The ninther takes 12 comparisons (three medians of three, then the median of those), and the partial insertion sort takes n − 1 to confirm the range is in order. Reversed input gets the same count because the 12 pivot swaps trigger the reversal, which compares nothing. All-equal input makes no swaps at all, so it looks sorted.
Unstable and deterministic
pdqsort moves elements across the slice while partitioning, so equal elements
can change order. Insertion sort keeps them, because it only swaps when
cmp returns a negative number
(L9-L16).
That gives a visible threshold at 12. This program sorts items whose keys go
0, 1, 0, 1, … and prints where the first six (all with key 0) came from:
package main
import (
"cmp"
"fmt"
"slices"
)
type item struct{ key, pos int }
// sortByKey sorts n items whose keys alternate 0, 1, 0, 1, ... and returns
// the original positions of the first six items, which all have key 0.
func sortByKey(n int, sort func([]item, func(a, b item) int)) []int {
xs := make([]item, n)
for i := range xs {
xs[i] = item{i % 2, i}
}
sort(xs, func(a, b item) int { return cmp.Compare(a.key, b.key) })
var pos []int
for _, x := range xs[:6] {
pos = append(pos, x.pos)
}
return pos
}
func main() {
for _, n := range []int{12, 13, 1000} {
fmt.Printf("n=%4d SortFunc %v SortStableFunc %v\n", n,
sortByKey(n, slices.SortFunc[[]item]),
sortByKey(n, slices.SortStableFunc[[]item]))
}
}
$ go run stable.go
n= 12 SortFunc [0 2 4 6 8 10] SortStableFunc [0 2 4 6 8 10]
n= 13 SortFunc [8 12 2 0 4 10] SortStableFunc [0 2 4 6 8 10]
n=1000 SortFunc [250 732 2 996 4 994] SortStableFunc [0 2 4 6 8 10]
At 12 elements the unstable sort happens to be stable; at 13 it isn’t. The
“random” swaps in breakPatterns come from an xorshift generator seeded with
the length of the range
(L243,
xorshift, sort.go L178-L186),
so there is no real randomness anywhere. The same input always comes out in
the same order. Running the program twice gave byte-identical output (same
MD5).
The stable sort
slices.SortStableFunc is a different algorithm
(stableCmpFunc, L335-L357).
It insertion-sorts blocks of 20 elements, then merges neighbouring blocks of
20, 40, 80 and so on with SymMerge (Kim and Kutzner, 2004), which merges in
place by rotating blocks instead of copying into a buffer. No extra memory,
at a price: the sort.Stable documentation promises O(n·log n) comparisons
but O(n·log² n) swaps
(sort.go L228-L229).
Is the generic one faster?
A million random ints, best of 7 runs each:
package main
import (
"cmp"
"fmt"
"math/rand/v2"
"slices"
"sort"
"time"
)
// best returns the fastest of 7 runs of f, each on a fresh copy of xs.
func best(xs []int, f func([]int)) time.Duration {
b := time.Hour
for range 7 {
x := slices.Clone(xs)
t := time.Now()
f(x)
b = min(b, time.Since(t))
}
return b
}
func main() {
r := rand.New(rand.NewPCG(1, 2))
xs := make([]int, 1_000_000)
for i := range xs {
xs[i] = r.IntN(1 << 30)
}
fmt.Println("slices.Sort ", best(xs, func(x []int) { slices.Sort(x) }))
fmt.Println("slices.SortFunc ", best(xs, func(x []int) { slices.SortFunc(x, cmp.Compare[int]) }))
fmt.Println("sort.Slice ", best(xs, func(x []int) {
sort.Slice(x, func(i, j int) bool { return x[i] < x[j] })
}))
fmt.Println("sort.Sort(IntSlice) ", best(xs, func(x []int) { sort.Sort(sort.IntSlice(x)) }))
fmt.Println("slices.SortStableFunc", best(xs, func(x []int) { slices.SortStableFunc(x, cmp.Compare[int]) }))
fmt.Println("sort.Stable(IntSlice)", best(xs, func(x []int) { sort.Stable(sort.IntSlice(x)) }))
}
$ go build -o timing timing.go && ./timing
slices.Sort 59.754208ms
slices.SortFunc 92.1515ms
sort.Slice 101.64575ms
sort.Sort(IntSlice) 104.723625ms
slices.SortStableFunc 227.1265ms
sort.Stable(IntSlice) 337.107667ms
With no function call per comparison, slices.Sort is the fastest by a
third. SortFunc beats sort.Slice by about 10%. The stable sort costs about
2.5 times the unstable one.
Curious facts
- The only “randomness” in Go’s unstable sort is an xorshift generator seeded with the length of the range, so it is fully deterministic.
- Already sorted, reversed and all-equal inputs of a million elements each cost exactly 1,000,011 comparisons.
- Up to 12 elements,
slices.SortFunckeeps equal elements in order, because it is just insertion sort there. At 13 it stops. slices.Sortputs NaNs before every other float (sort.go L14-L15), andcmp.Comparetreats a NaN as equal to a NaN and -0.0 as equal to 0.0 (cmp.go L32-L59).- The
sortandslicessorts are generated from the same template, so a fix to one reaches both aftergo generate.
History
- Go 1.19 (2022-08-02): “The sorting algorithm has been rewritten to use pattern-defeating quicksort.”
- Go 1.21 (2023-08-08): new
slices,mapsandcmppackages, withslices.Sort,SortFunc,SortStableFuncandcmp.Compare. - Go 1.22 (2024-02-06):
sort.Ints,sort.Float64sandsort.Stringsbecome wrappers aroundslices.Sort;cmp.Oris added. - Go 1.23 (2024-08-13): iterators;
slices.Sortedandslices.SortedFunccollect an iterator into a sorted slice.
Sources
src/slices/zsortanyfunc.goat go1.27.4: insertion sort, heapsort, pdqsort, partition, partitionEqual, partial insertion sort, breakPatterns, choosePivot, stable sort, SymMergesrc/slices/sort.goat go1.27.4: Sort, SortFunc, SortStableFunc, sortedHint and xorshift;zsortordered.gosrc/sortat go1.27.4:gen_sort_variants.go,slice.go,sort.goSort, Ints and friends, Stablesrc/cmp/cmp.go- Release notes: Go 1.19, Go 1.21, Go 1.22, Go 1.23 (slices); dates from the release history
- pdqsort paper, linked from the source: arXiv:2106.05123
grep -rl /lib/go/sorting/
ls go/
- draft How Go maps work: Swiss tables since Go 1.24What go1.27's built-in map does with your keys: 8-slot groups with control bytes, tables capped at 1024 slots, a directory of tables, and an iteration order that is a random rotation of a fixed one.