...
1package sort
2
3type orderedSlice[Elem comparable] []Elem
4
5func (s orderedSlice[Elem]) Len() int { return len(s) }
6func (s orderedSlice[Elem]) Less(i, j int) bool { return s[i] < s[j] }
7func (s orderedSlice[Elem]) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
8
9// OrderedSlice sorts the slice s in ascending order.
10// The elements of s must be ordered using the < operator.
11func OrderedSlice[Elem comparable](s []Elem) {
12 sort.Sort(orderedSlice[Elem](s))
13}
14
15type sliceFn[Elem any] struct {
16 s []Elem
17 f func(Elem, Elem) bool
18}
19
20func (s sliceFn[Elem]) Len() int { return len(s.s) }
21func (s sliceFn[Elem]) Less(i, j int) bool { return s.f(s.s[i], s.s[j]) }
22func (s sliceFn[Elem]) Swap(i, j int) { s.s[i], s.s[j] = s.s[j], s.s[i] }
23
24// SliceFn sorts the slice s according to the function f.
25func SliceFn[Elem any](s []Elem, f func(Elem, Elem) bool) {
26 Sort(sliceFn[Elem]{s, f})
27}
View as plain text