欢迎来到我的博客,愿共同成长!!!

信徒

路虽远,行则将至

对字节流切片进行排序

为了方便,我们借助Golang标准库提供的sort包进行排序。

为了使用sort进行排序,我们需要实现该包中的Interface接口,该接口的代码如下:

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less reports whether the element with
    // index i should sort before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

想要实现这个接口,我们要将我们需要排序的切片类型定义成自定义类型,然后该类型实现上述接口的三个方法,代码如下:

// bytesSlice implements sort.Interface. And we can sort bytes slice by
// converting it to bytesSlice explicitly using sort.Sort().

type bytesSlice [][]byte

// Less compares two byte slices(bs[i] and bs[j]) by comparing their
// elements one by one.
func (bs bytesSlice) Less(i, j int) bool {
    var k int
    for k = 0; k < len(bs[i]) && k < len(bs[j]); k++ {
        if bs[i][k] < bs[j][k] {
            return true
        }
    }
    if k < len(bs[i]) {
        return false
    }

    return true
}

func (bs bytesSlice) Len() int {
    return len(bs)
}

func (bs bytesSlice) Swap(i, j int) {
    bs[i], bs[j] = bs[j], bs[i]
}

完成了以上工作之后,我们就可以调用sort.Sort()对目标对象进行排序了,但是需要将其显示转化成自定义类型(对应上述代码中的bytesSlice)。代码如下:

sort.Sort(bytesSlice(object))
posted @ 2019-12-25 17:50  LeslieRan  阅读(170)  评论(0)    收藏  举报