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

How Can I Sort a 2D Array in Go?

Linda Hamilton
Release: 2024-11-26 00:30:10
Original
292 people have browsed it

How Can I Sort a 2D Array in Go?

Sorting a Two-Dimensional Array in Go

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)
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template