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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.