stable sort

This commit is contained in:
xing 2023-05-10 17:02:58 +08:00
parent 40451970a0
commit 65a0ca94f6
2 changed files with 69 additions and 1 deletions

View File

@ -34,7 +34,14 @@ func Sort[T any](arr []T, fn func(i, j T) bool) {
fn: fn,
}
sort.Sort(slice)
return
}
func StableSort[T any](arr []T, fn func(i, j T) bool) {
slice := anyArr[T]{
data: arr,
fn: fn,
}
sort.Stable(slice)
}
func Sorts[T constraints.Ordered](a []T, order int) {

View File

@ -102,3 +102,64 @@ func TestSorts(t *testing.T) {
})
}
}
func TestStableSort(t *testing.T) {
type xy struct {
x int
y int
}
type args[T any] struct {
arr []T
fn func(i, j T) bool
}
type testCase[T any] struct {
name string
args args[T]
wantR []T
}
tests := []testCase[xy]{
{
name: "t1",
args: args[xy]{
arr: []xy{
{1, 2},
{3, 4},
{1, 3},
{2, 1},
{1, 6},
},
fn: func(i, j xy) bool {
if i.x < j.x {
return true
}
if i.x == j.x && i.y > i.y {
return true
}
return false
},
},
wantR: []xy{
{1, 2},
{1, 3},
{1, 6},
{2, 1},
{3, 4},
},
},
{
name: "t1",
args: args[xy]{
arr: []xy{{1, 2}, {1, 3}, {1, 6}},
fn: func(i, j xy) bool {
return i.x > j.x
},
},
wantR: []xy{{1, 2}, {1, 3}, {1, 6}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
StableSort(tt.args.arr, tt.args.fn)
})
}
}