Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go lang sort a 2D Array

Tags:

arrays

go

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

For example If I have,

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

Then is there something like,

sort.Sort(matrix)
like image 881
Shinchan Avatar asked May 07 '26 00:05

Shinchan


2 Answers

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)
}

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)
like image 182
JimB Avatar answered May 10 '26 14:05

JimB


Consider You have a m*n matrix and you want to sort based on kth column

sort.SliceStable(rangearray, func(i, j int) bool {
        return rangearray[i][k] < rangearray[j][k]
})

In the same way you want to sort the m*n matrix and you want to sort based on kth row

sort.SliceStable(rangearray, func(i, j int) bool {
        return rangearray[k][i] < rangearray[k][j]
})
like image 21
mourya venkat Avatar answered May 10 '26 15:05

mourya venkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!