Sorters - craterdog/go-component-framework GitHub Wiki
Overview
A sorter is an agent that can be used to sort the values in an intrinsic Go array. The agent sorts the values in place using an iterative merge sort along with a ranking function associated with the sorter. The algorithm is documented here.
This iterative approach saves on memory allocation by swapping between two Go arrays of the same size rather than allocating new Go arrays for each sub-array. This results in stable O[nlog(n)] time and O[n] space performance.
A Quick Example
To whet your appetite, here is some short example code that demonstrates the use of sorter agents.
package main
import (
fmt "fmt"
fra "github.com/craterdog/go-component-framework/v7"
)
func main() {
// Create a new sorter with the default (natural ordering) ranker.
var sorter = fra.Sorter[string]()
// Create an array containing greek letters.
var letters = []string{
"alpha",
"beta",
"gamma",
"delta",
"epsilon",
"zeta",
"eta",
"theta",
}
fmt.Println(letters)
// Sort the letters in alphabetical order.
sorter.SortValues(letters)
fmt.Println(letters)
// Sort the letters in reverse alphabetical order.
sorter.ReverseValues(letters)
fmt.Println(letters)
// Shuffle the order of the letters.
sorter.ShuffleValues(letters)
fmt.Println(letters)
// Create a new sorter with a custom ranking function.
sorter = fra.SorterWithRanker[string](
func(first, second string) fra.Rank {
switch {
case first[1:] < second[1:]:
return fra.LesserRank
case first[1:] > second[1:]:
return fra.GreaterRank
default:
return fra.EqualRank
}
},
)
// Sort the letters by their second character.
sorter.SortValues(letters)
fmt.Println(letters)
}