go排序示例

package main

import(
        "fmt"
        "sort"
        "math/rand"
)


const(
        male   =  iota
        female
        unknown
)
var genderStr []string=[]string{"male","female","unknown",}



type People struct{
        Id int `ID`
        Age int `Age`
        Name string `Name`
        Gender int `Gender`
}
func (p People) String() string{
        return fmt.Sprintf("People %q of age %v with ID %v,Gender %s\n",p.Name,p.Age,p.Id,genderStr[p.Gender])
}



type Classmate []People
func (c Classmate) Len() int { return len(c) }
func (c Classmate) Less(i,j int) bool { return c[i].Age<c[j].Age }
func (c Classmate) Swap(i,j int) { c[i],c[j]=c[j],c[i] }





func main(){
        cs:=make (Classmate,10,20)


        for  i:=0;i<len(cs); i++ {
                cs[i].Id=i
                cs[i].Age=rand.Intn(50)
                cs[i].Name=fmt.Sprintf("cs_%v",i)
                cs[i].Gender=rand.Intn(3)
        }
        fmt.Println(cs)

        sort.Sort(cs)
        fmt.Println(cs)

}






Screen output sample:

[People "cs_0" of age 31 with ID 0,Gender male
 People "cs_1" of age 47 with ID 1,Gender unknown
 People "cs_2" of age 31 with ID 2,Gender male
 People "cs_3" of age 25 with ID 3,Gender unknown
 People "cs_4" of age 6 with ID 4,Gender male
 People "cs_5" of age 44 with ID 5,Gender female
 People "cs_6" of age 12 with ID 6,Gender unknown
 People "cs_7" of age 28 with ID 7,Gender unknown
 People "cs_8" of age 11 with ID 8,Gender unknown
 People "cs_9" of age 37 with ID 9,Gender unknown
]
[People "cs_4" of age 6 with ID 4,Gender male
 People "cs_8" of age 11 with ID 8,Gender unknown
 People "cs_6" of age 12 with ID 6,Gender unknown
 People "cs_3" of age 25 with ID 3,Gender unknown
 People "cs_7" of age 28 with ID 7,Gender unknown
 People "cs_0" of age 31 with ID 0,Gender male
 People "cs_2" of age 31 with ID 2,Gender male
 People "cs_9" of age 37 with ID 9,Gender unknown
 People "cs_5" of age 44 with ID 5,Gender female
 People "cs_1" of age 47 with ID 1,Gender unknown

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值