In Go, sorting a two-dimensional array requires defining a custom sorting criterion. One approach is to implement the sort.Interface to provide the necessary methods for sorting:
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] }
Here, Matrix implements sort.Interface by defining the Len(), Less(), and Swap() methods. Len() returns the length of the matrix, Less() compares two rows of the matrix element-wise, and Swap() swaps two rows.
func main() { m := Matrix(matrix) sort.Sort(&m) }
In this example, matrix is a predefined two-dimensional array, and m is a copy of matrix that implements sort.Interface. By passing &m to sort.Sort(), the matrix is sorted in-place.
Another approach is to use the sort.Slice() function:
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)
Here, matrix[:] converts the matrix to a slice, and the provided anonymous function defines the sorting criterion. By passing the slice and the function to sort.Slice(), the matrix is sorted in-place.
The above is the detailed content of How to Sort a 2D Array in Go?. For more information, please follow other related articles on the PHP Chinese website!