只要实现了Sortable接口的所有方法,就可以使用该接口的函数。
我们通过冒泡排序来演示一下:
package main
import "fmt"
type Sortable interface {
Len() int
Less(int, int) bool
Swap(int, int)
}
func Mysort(s Sortable) {
l := s.Len()
for x := 0; x < l; x++ {
for y := 0; y < l-x-1; y++ {
if s.Less(y, y+1) {
s.Swap(y, y+1)
}
}
}
}
//实现整形数组的排序
type myInt []int
func (myint myInt) Len() int {
return len(myint)
}
func (myint myInt) Less(i, j int) bool {
return myint[i] < myint[j]
}
func (myint myInt) Swap(i, j int) {
myint[i], myint[j] = myint[j], myint[i]
}
//实现字符串长度的排序
type myString []string
func (mystring myString) Len() int {
return len(mystring)
}
func (mystring myString) Less(i, j int) bool {
return len(mystring[i]) < len(mystring[j])
}
func (mystring myString) Swap(i, j int) {
mystring[i], mystring[j] = mystring[j], mystring[i]
}
func main() {
a := myInt{6, 2, 5, 1, 3, 4}
Mysort(a)
fmt.Println(a)
s := myString{"sun", "w", "qiang", "qq"}
Mysort(s)
fmt.Println(s)
}