Library contents

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

  1. Start with A with rank 2, B with rank 1, C with rank 2
  2. Do this Stable sort by rank
  3. Result B, A, C
B moves to the front. A and C tie, so their original order is preserved.

Syntax

Go 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.

From the programjobs := []job{{"pack", 2}, {"inspect", 1}, {"ship", 2}}
First output lineinspect
main.go
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)
	}
}
Output
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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result0 · 2 · 6 · 6

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?

Given3 · 0 · 8 · 3
Worked result0 · 3 · 3 · 8