加入收藏 | 设为首页 | 会员中心 | 我要投稿 淮北站长网 (https://www.0561zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Go语言排序与接口实例分析

发布时间:2016-12-04 16:09:04 所属栏目:教程 来源:站长网
导读:本文实例讲述了Go语言排序与接口用法。分享给大家供大家参考。具体如下: 复制代码 代码如下:import "fmt" type Sorter interface { nbsp; Len() int nbsp; Less(i, j int) bool nbsp; Swap(i, j int) } type Xi []int type Xs []string func (p Xi) Len()

本文实例讲述了Go语言排序与接口用法。分享给大家供大家参考。具体如下:

复制代码 代码如下:import "fmt"
type Sorter interface {
nbsp; Len() int
nbsp; Less(i, j int) bool
nbsp; 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] lt; 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] lt; p[i] }
func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[i] }
func Sort(x Sorter) {
nbsp; for i := 0; i lt; x.Len() - 1; i++ {
nbsp;nbsp;nbsp; for j := i + 1; j lt; x.Len(); j++ {
nbsp;nbsp;nbsp;nbsp;nbsp; if x.Less(i, j) {
nbsp;nbsp;nbsp;nbsp;nbsp;nbsp;nbsp; x.Swap(i, j)
nbsp;nbsp;nbsp;nbsp;nbsp; }
nbsp;nbsp;nbsp; }
nbsp; }
}
func main() {
nbsp; ints := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}
nbsp; strings := Xs{"nut", "ape", "elephant", "zoo", "go"}
nbsp; Sort(ints)
nbsp; fmt.Printf("%vn", ints)
nbsp; Sort(strings)
nbsp; fmt.Printf("%vn", strings)
}

希望本文所述对大家的Go语言程序设计有所帮助。

(编辑:淮北站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读