From 65a0ca94f64b93d10bc476ab52cc205bd800d718 Mon Sep 17 00:00:00 2001 From: xing Date: Wed, 10 May 2023 17:02:58 +0800 Subject: [PATCH] stable sort --- helper/slice/sort.go | 9 +++++- helper/slice/sort_test.go | 61 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/helper/slice/sort.go b/helper/slice/sort.go index 2fa0c41..834b2b8 100644 --- a/helper/slice/sort.go +++ b/helper/slice/sort.go @@ -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) { diff --git a/helper/slice/sort_test.go b/helper/slice/sort_test.go index 18a58f6..5ebfcc4 100644 --- a/helper/slice/sort_test.go +++ b/helper/slice/sort_test.go @@ -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) + }) + } +}