๐Ÿ”ขSorting with the sort PackageLESSON

Sorting with the sort Package

Go's sort package provides in-place sorting for slices of primitives, a flexible closure-based API for structs, an interface for custom types, and a binary search primitive โ€” all in the standard library.

Sorting primitives

All three functions sort in-place and in ascending order. If you need to preserve the original, copy the slice first.

sort.Slice โ€” sorting structs by any field

The most-used function in the package:

The less function receives indices i and j; return true if element i should come before j.

sort.SliceStable โ€” preserve original order of equal elements

Use SliceStable when equal elements have meaningful relative order (e.g., sort by department then preserve original name order within each department).

Multi-key sort

Chain comparisons in the less function:

sort.Interface โ€” custom types

Implement three methods to make any type sortable with sort.Sort:

Prefer sort.Slice for one-off sorts; implement sort.Interface when the type is always sorted the same way or needs to be passed to functions expecting sort.Interface.

sort.Search โ€” binary search

sort.Search runs binary search in O(log n). The slice must be sorted. The function must be monotone: false for indices before the answer, true from the answer onwards.

sort.Reverse

Checking if sorted

Knowledge Check

What does the less function passed to sort.Slice(s, less) return?

When should you use sort.SliceStable instead of sort.Slice?

What must be true about the slice passed to sort.Search?