zoukankan      html  css  js  c++  java
  • go 自定义排序

    go可以利用切片,实现自定义的排序

    1 声明一个切片类型

    2 对切片类型绑定 Len Less Swap三个方法

    3 调用sort.Sort方法

    package main
    
    import (
        "fmt"
        "math/rand"
        "sort"
        "strconv"
        "time"
    )
    
    type Student2 struct {
        Name string
        Age int
        Score float64
    }
    
    type Student2s []Student2
    
    func (stu2s Student2s) Len() int {
        return len(stu2s)
    }
    func (stu2s Student2s) Less(i,j int)  bool{
        return stu2s[i].Score<stu2s[j].Score
    }
    func (stu2s Student2s) Swap(i,j int)  {
    
        stu2s[i],stu2s[j] = stu2s[j],stu2s[i]
    }
    func (stu2s Student2s) String () string {
        var str string
    
        for i:=1;i<len(stu2s);i++{
            str += stu2s[i].Name+"	年龄:"+strconv.Itoa(stu2s[i].Age)+"	成绩:"+strconv.FormatFloat(stu2s[i].Score,'f',2,64)
            str += "
    "
        }
        return str
    }
    func main() {
        rand.Seed(time.Now().UnixNano())
        var stu2s Student2s
        for i:=0;i<5;i++ {
            stu := Student2{
                Name:  fmt.Sprintf("学生 %d", i),
                Age:   rand.Intn(100),
                Score: rand.Float64()*100,
            }
            stu2s = append(stu2s, stu)
        }
            fmt.Println(stu2s)
            sort.Sort(stu2s)
            fmt.Println(stu2s)
    
    }
    View Code

    这里注意在使用随机数的时候,要初始化随机数的种子,不然每次随机的结果都是一样的

    rand.Seed(time.Now().UnixNano())
  • 相关阅读:
    spring MVC配置详解
    使用JDBC连接各种数据库
    Linux Shell常用shell命令
    IOS返回go(-1)
    NFS客户端挂载
    oracle常用函数
    支付宝手机网站支付流程(Node实现)
    SQL中的case when then else end用法
    mysql
    socket
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/14333993.html
Copyright © 2011-2022 走看看