Skip to content

Commit 0c20a4d

Browse files
committed
Fix sort with key implementations
1 parent 2195493 commit 0c20a4d

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

tools/utils/misc.go

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -75,22 +75,29 @@ func StableSort[T any](s []T, less func(a, b T) bool) []T {
7575
return s
7676
}
7777

78-
func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
79-
mem := make([]C, len(s))
78+
func sort_with_key[T any, C constraints.Ordered](impl func(any, func(int, int) bool), s []T, key func(a T) C) []T {
79+
temp := make([]struct {
80+
key C
81+
val T
82+
}, len(s))
8083
for i, x := range s {
81-
mem[i] = key(x)
84+
temp[i].val, temp[i].key = x, key(x)
85+
}
86+
impl(temp, func(i, j int) bool {
87+
return temp[i].key < temp[j].key
88+
})
89+
for i, x := range temp {
90+
s[i] = x.val
8291
}
83-
sort.Slice(s, func(i, j int) bool { return mem[i] < mem[j] })
8492
return s
8593
}
8694

95+
func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
96+
return sort_with_key(sort.Slice, s, key)
97+
}
98+
8799
func StableSortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
88-
mem := make([]C, len(s))
89-
for i, x := range s {
90-
mem[i] = key(x)
91-
}
92-
sort.SliceStable(s, func(i, j int) bool { return mem[i] < mem[j] })
93-
return s
100+
return sort_with_key(sort.SliceStable, s, key)
94101
}
95102

96103
func Max[T constraints.Ordered](a T, items ...T) (ans T) {

0 commit comments

Comments
 (0)