
go语言中运用接口实现sort的通用方法
-
定义一个的用于排序的通用接口
1
2
3
4
5type Sorter interface{
Len() int
Less(i, j int) bool
Swap(i, j int)
} -
定义用于排序的slice新类型
type Xi []int
type Xs []string - 实现Sorter接口的方法
int类型
1
2
3func (p Xi) Len() int {return len(p)}
func (p Xi) Less(i, j int) bool {return p[j] < p[i]}
func (p Xi) Swap(i, j int){p[i], p[j] = p[j], p[i]}
string类型
1 |
func (p Xs) Len() int {return len(p)} |
- 编写用于Sorter接口的通用排序函数
1
2
3
4
5
6
7
8
9func Sort(x Sorter){
for i:= 0; i < x.Len(); i++{
for j:= i + 1; j < x.Len(); j++{
if x.Less(i, j){
x.Swap(i, j)
}
}
}
}
go语言中sort方法的实现
看一下从大到小的排序的实现
1 |
type reverse struct { Sorter } |




近期评论