1
2
3
4
5
6
7 package mysort
8
9 import (
10 "fmt"
11 )
12
13 type LessConstraint[T any] interface {
14 Less(T) bool
15 }
16
17
18 func Sort[T LessConstraint[T]](x []T) {
19 n := len(x)
20 for i := 1; i < n; i++ {
21 for j := i; j > 0 && x[j].Less(x[j-1]); j-- {
22 x[j], x[j-1] = x[j-1], x[j]
23 }
24 }
25 }
26
27 type MyInt struct {
28 Value int
29 }
30
31 func (a *MyInt) Less(b *MyInt) bool {
32 return a.Value < b.Value
33 }
34
35
36 func F() {
37 sl1 := []*MyInt{&MyInt{4}, &MyInt{3}, &MyInt{8}, &MyInt{7}}
38 Sort(sl1)
39 fmt.Printf("%v %v %v %v\n", sl1[0], sl1[1], sl1[2], sl1[3])
40 }
41
View as plain text