简单排序

This commit is contained in:
xing 2022-10-25 20:05:44 +08:00
parent f37901f85f
commit 87758d77a8
2 changed files with 57 additions and 0 deletions

View File

@ -8,6 +8,7 @@ import (
"math/rand"
"reflect"
"regexp"
"sort"
"strings"
)
@ -261,3 +262,29 @@ func RandNum[T IntNumber](start, end T) T {
end++
return T(rand.Int63n(int64(end-start))) + start
}
type anyArr[T any] struct {
data []T
fn func(i, j T) bool
}
func (r anyArr[T]) Len() int {
return len(r.data)
}
func (r anyArr[T]) Swap(i, j int) {
r.data[i], r.data[j] = r.data[j], r.data[i]
}
func (r anyArr[T]) Less(i, j int) bool {
return r.fn(r.data[i], r.data[j])
}
func SampleSort[T any](arr []T, fn func(i, j T) bool) {
slice := anyArr[T]{
data: arr,
fn: fn,
}
sort.Sort(slice)
return
}

View File

@ -607,3 +607,33 @@ func TestRandNum(t *testing.T) {
})
}
}
func TestSampleSort(t *testing.T) {
type args struct {
arr []int
fn func(i, j int) bool
}
tests := []struct {
name string
args args
wantR []int
}{
{
name: "t1",
args: args{
arr: []int{3, 5, 6, 1},
fn: func(i, j int) bool {
return i < j
},
},
wantR: []int{1, 3, 5, 6},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if SampleSort(tt.args.arr, tt.args.fn); !reflect.DeepEqual(tt.args.arr, tt.wantR) {
t.Errorf("SampleSort() = %v, want %v", tt.args.arr, tt.wantR)
}
})
}
}