Stable Sort Keeps Equal Order

Use slices.SortStableFunc when equal keys must keep their input order: unstable SortFunc may reorder records that compare the same.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"cmp"
	"fmt"
	"slices"
)

type Ticket struct {
	Priority int
	Owner    string
}

func main() {
	tickets := []Ticket{
		{2, "ana"},
		{1, "bob"},
		{2, "cid"},
		{1, "dee"},
	}

	// 稳定排序:优先级相同时保持录入顺序 bob 之后 dee
	slices.SortStableFunc(tickets, func(a, b Ticket) int {
		return cmp.Compare(a.Priority, b.Priority)
	})
	fmt.Println("stable:", tickets)

	// 非稳定排序结果合法,但同优先级内部的相对顺序不承诺
	shuffled := []Ticket{{2, "ana"}, {1, "bob"}, {2, "cid"}, {1, "dee"}}
	slices.SortFunc(shuffled, func(a, b Ticket) int {
		return cmp.Compare(a.Priority, b.Priority)
	})
	fmt.Println("sort:  ", shuffled)
}

How it works

Stable Sort Keeps Equal Order reduces to the function main.

Using it

Each line comes labeled — stable:, sort: — when the file runs.

Output is labeled for readability — expect lines prefixed with stable:, sort:.

Key statements

return cmp.Compare(a.Priority, b.Priority)

Interactive Tools for This Topic

FAQ

What does Stable Sort Keeps Equal Order print when run?
Execute the whole file; each printed line is prefixed with a label like `stable:`, `sort:`.