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)
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)
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]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With