Sorting a multidimensional array can be achieved in Go by manually defining how you want the sorting to occur. Two approaches can be taken:
1. Implementing the sort.Sort Interface:
Create custom methods for Len, Less, and Swap to use with sort.Sort, enabling you to modify the array values during sorting. For example:
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) }
2. Using the sort.Slice Function:
Convert the array to a slice and provide a comparable function for sort.Slice to handle the sorting. For instance:
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)
Both approaches enable you to customize the sorting behavior of your two-dimensional array in Go.
The above is the detailed content of How Can I Sort a 2D Array in Go?. For more information, please follow other related articles on the PHP Chinese website!