Master Go’s sort Package: Implement Custom Sorting with Interface
This article explains how Go's sort package internally uses four algorithms, how to implement sort.Interface with Len, Less, and Swap methods, and provides code examples for sorting int slices and custom structs by different fields.
The Go sort package implements four basic sorting algorithms—Insertion Sort, Merge Sort, Heap Sort, and Quick Sort—and automatically selects the optimal one based on the data. To use it, you only need to implement the sort.Interface with Len, Less, and Swap methods.
Source Code
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}Example: sorting a slice of int using the built‑in IntSlice type, which uses Quick Sort.
type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p IntSlice) Sort() { Sort(p) }The generic Sort function calls quickSort after determining the length, performing O(n·log n) calls to Less and Swap. The sort is not guaranteed to be stable.
Custom Slice Example
Define a struct TDepartment and a slice type TDepartmentSlice, implement Len, Less, and Swap to sort by DeptId or by creation time.
type TDepartment struct {
DeptId int64
CreateTime string
// other fields omitted
}
type TDepartmentSlice []*TDepartment
func (p TDepartmentSlice) Len() int { return len(p) }
func (p TDepartmentSlice) Less(i, j int) bool { return p[i].DeptId < p[j].DeptId }
func (p TDepartmentSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }A wrapper SortTDepartmentSliceByCreateTime implements Less by parsing the CreateTime strings and comparing timestamps.
type SortTDepartmentSliceByCreateTime struct { TDepartmentSlice }
func (s SortTDepartmentSliceByCreateTime) Less(i, j int) bool {
t1, _ := time.Parse("2006-01-02 15:04:05", s.TDepartmentSlice[i].CreateTime)
t2, _ := time.Parse("2006-01-02 15:04:05", s.TDepartmentSlice[j].CreateTime)
return t1.Unix() < t2.Unix()
}The main function demonstrates printing the slice before and after sorting by DeptId and then by creation time.
Summary
To sort a slice, implement the sort.Interface methods.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
