朗朗排序2D阵列 [英] Go lang sort a 2D Array

查看:61
本文介绍了朗朗排序2D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go中对二维数组进行排序.谁能建议我该怎么做?

I want to sort a two dimensional array in Go. Can anyone please suggest how I can go about this?

例如,如果有,

var matrix [3][3]int{
  {2,3,1},
  {6,3,5},
  {1,4,9}
}

然后有类似的东西,

sort.Sort(matrix)

推荐答案

您必须定义如何自己对这种类型进行排序.您可以创建必要的方法来使用sort.Sort接口,并根据需要使用指针来更改数组值:

You have to define how to sort this type yourself. You can either create the necessary methods to use the sort.Sort interface, using a pointer as necessary to mutate the array values: https://play.golang.org/p/thdf-k2k3o

type Matrix [3][3]int

func (m Matrix) Len() int { return len(m) }
func (m Matrix) Less(i, j int) bool {
    for x := range m[i] {
        if m[i][x] == m[j][x] {
            continue
        }
        return m[i][x] < m[j][x]
    }
    return false
}

func (m *Matrix) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func main() {
    m := Matrix(matrix)
    sort.Sort(&m)
}

或使用sort.Slice函数,将matrix转换为切片并提供适当的较少函数: https://play.golang.org/p/4hrghm9gib

Or use the sort.Slice function, converting matrix to a slice and providing an appropriate less function: https://play.golang.org/p/4hrghm9gib

sort.Slice(matrix[:], func(i, j int) bool {
    for x := range matrix[i] {
        if matrix[i][x] == matrix[j][x] {
            continue
        }
        return matrix[i][x] < matrix[j][x]
    }
    return false
})

fmt.Println(matrix)

这篇关于朗朗排序2D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆