Utility function to sort with key

This commit is contained in:
Kovid Goyal
2022-09-21 11:00:40 +05:30
parent e7f38929d9
commit b1e08adbce
3 changed files with 29 additions and 6 deletions

View File

@@ -5,6 +5,8 @@ package utils
import (
"fmt"
"sort"
"golang.org/x/exp/constraints"
)
var _ = fmt.Print
@@ -33,3 +35,21 @@ func StableSort[T any](s []T, less func(a, b T) bool) []T {
sort.SliceStable(s, func(i, j int) bool { return less(s[i], s[j]) })
return s
}
func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
mem := make([]C, len(s))
for i, x := range s {
mem[i] = key(x)
}
sort.Slice(s, func(i, j int) bool { return mem[i] < mem[j] })
return s
}
func StableSortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
mem := make([]C, len(s))
for i, x := range s {
mem[i] = key(x)
}
sort.SliceStable(s, func(i, j int) bool { return mem[i] < mem[j] })
return s
}