golang排序实现 sort接口实现

转:http://www.dotcoo.com/golang-sort

今天看见群里再讨论排序的sort.Interface的实现,有童鞋一直搞不定,我就上手了一下,哦耶搞定了,代码放在这里.

其实很简单sort.Interface借口有三个方法,给自己的struct实现这三个方法,然后用将自己的结构体传给sort.Sort方法就排序完成.

当然sort包也有几个常用的方法sort.Float64Slice sort.IntSlise sort.StringSlise,呵呵

package main
                 
import (
    "fmt"
    "sort"
)
                 
type MapSorter []Item
                 
type Item struct {
    Key string
    Val int64
}
                 
func NewMapSorter(m map[string]int64) MapSorter {
    ms := make(MapSorter, 0, len(m))
                 
    for k, v := range m {
        ms = append(ms, Item{k, v})
    }
                 
    return ms
}
                 
func (ms MapSorter) Len() int {
    return len(ms)
}
                 
func (ms MapSorter) Less(i, j int) bool {
    return ms[i].Val < ms[j].Val // 按值排序
    //return ms[i].Key < ms[j].Key // 按键排序
}
                 
func (ms MapSorter) Swap(i, j int) {
    ms[i], ms[j] = ms[j], ms[i]
}
                 
func main(){
    m  := map[string]int64 {
        "e": 10,
        "a": 2,
        "d": 15,
        "c": 8,
        "f": 1,
        "b": 12,
    }
                 
    ms := NewMapSorter(m)
    sort.Sort(ms)
                 
    for _, item := range ms {
        fmt.Printf("%s:%d\n", item.Key, item.Val)
    }
}

下面实现一个简单的计算区间覆盖长度的问题
    m  := map[float64]float64 {
        1.0: 2.0,
        5.1: 6.5,
        2.3: 3.1,
        4.3: 4.8,
        4.4: 4.5,
        9.5: 12.0,
    }
    ms := NewMapSorter(m)
    sort.Sort(ms)
    e,t := 0.0, 0.0
    for _, item := range ms {
        if item.Key <= e && item.Val > e {
            t = t + item.Val - e
        } else if e < item.Key {
            t = t + item.Val - item.Key
        }
        if item.Val > e {
            e = item.Val
        }
        fmt.Printf("%v,%v\n",e,t)
        fmt.Printf("%v:%v\n", item.Key, item.Val)
    }
    fmt.Printf("%v\n", t)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值