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

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

发布时间:2020-12-16 19:32:40 所属栏目:大数据 来源:网络整理
导读:本篇章节讲解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)

本篇章节讲解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,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("%vn",ints)
  Sort(strings)
  fmt.Printf("%vn",strings)
}

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

(编辑:李大同)

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

    推荐文章
      热点阅读