package main
import "fmt"
type Sorter interface {
Len() int
Less(i,j int) bool
Swap(i,j int)
}
type si []int
type ss []string
func (x si)Len()int{
return len(x)
}
func (x si)Less(i,j int)bool{return x[j]<x[i]}
func (x si)Swap(i,j int){x[i],x[j] = x[j],x[i]}
func (x ss)Len()int{
return len(x)
}
func (x ss)Less(i,j int)bool{return x[j]<x[i]}
func (x ss)Swap(i,j int){x[i],x[j] = x[j],x[i]}
func Sort(x Sorter){
for i := 0; i<x.Len()-1; i++ {
for j := i+1; j<x.Len(); j++ {
if x.Less(i, j) {
x.Swap(i,j)
}
}
}
}
func main(){
ints := si{3,7,9,5,6,1,8}
strings := ss{"apple","iphone","samsung","lg"}
Sort(ints)
fmt.Println(ints)
Sort(strings)
fmt.Println(strings)
}
有疑问加站长微信联系(非本文作者)