Home >Backend Development >Golang >How to Sort a 2D Array in Go?

How to Sort a 2D Array in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 18:52:15260browse

How to Sort a 2D Array in Go?

Sorting a Two-Dimensional Array in Go

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn