Go slices.SortStableFunc
slices.SortStableFunc reorders a slice in place using a three-way comparator. Jobs judged equal retain their original relative order.
A simple example
slices.SortStableFunc
- Start with A with rank 2, B with rank 1, C with rank 2
- Do this Stable sort by rank
- Result B, A, C
Syntax
slices.SortStableFunc(jobs, compare)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Rank jobs without disturbing ties
A queue or leaderboard contains entries with equal primary scores. Specify how ties are handled so the final ordering is predictable and preserves arrival order when the task requires it.
package main
import (
"cmp"
"fmt"
"slices"
)
func main() {
type job struct {
name string
priority int
}
jobs := []job{{"pack", 2}, {"inspect", 1}, {"ship", 2}}
slices.SortStableFunc(jobs, func(a, b job) int {
return cmp.Compare(a.priority, b.priority)
})
for _, j := range jobs {
fmt.Println(j.name)
}
}
inspect pack ship
cmp.Compare returns the sign of an ordering without subtracting potentially extreme integers. The two priority-two jobs stay in arrival order.
Go documentation for slices.SortStableFunc
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?
Review print quantities
A print room records four job quantities, including a cancelled job. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?