Go语言排序与接口实例分析
时间:2021-01-25 10:29:15|栏目:Golang|点击: 次
本文实例讲述了Go语言排序与接口用法。分享给大家供大家参考。具体如下:
复制代码 代码如下:
import "fmt"
type Sorter interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
type Xi []int
type Xs []string
func (p Xi) Len() int { return len(p) }
func (p Xi) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xi) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func (p Xs) Len() int { return len(p) }
func (p Xs) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[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 := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
strings := Xs{"nut", "ape", "elephant", "zoo", "go"}
Sort(ints)
fmt.Printf("%v\n", ints)
Sort(strings)
fmt.Printf("%v\n", strings)
}
type Sorter interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
type Xi []int
type Xs []string
func (p Xi) Len() int { return len(p) }
func (p Xi) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xi) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func (p Xs) Len() int { return len(p) }
func (p Xs) Less(i int, j int) bool { return p[j] < p[i] }
func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[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 := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
strings := Xs{"nut", "ape", "elephant", "zoo", "go"}
Sort(ints)
fmt.Printf("%v\n", ints)
Sort(strings)
fmt.Printf("%v\n", strings)
}
希望本文所述对大家的Go语言程序设计有所帮助。
上一篇:GO语io包的常用接口
栏 目:Golang
下一篇:Go语言的文件操作代码汇总
本文标题:Go语言排序与接口实例分析
本文地址:http://www.codeinn.net/misctech/50993.html