Sorting in Go

Go: Sorting

Sorting is a common task in programming, and Go provides a built-in sort package that makes it easy to sort slices of various types.

The sort package provides functions to sort slices of various data types, including strings, integers, and structs, in ascending or descending order.

How to sort a slice of integers in Go

Here's an example of how to use the sort package to sort a slice of integers in ascending order:

    package main

    import (
        "fmt"
        "sort"
    )

    func main() {
        nums := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}

        // Sort the slice in ascending order
        sort.Ints(nums)

        fmt.Println(nums) // Output: [1 1 2 3 3 4 5 5 5 6 9]
    }

Explainations: In above example, we define a slice of integers nums, and then call the sort.Ints() function to sort the slice in ascending order. The sorted slice is then printed to the console using the fmt.Println() function.

How to sort a slice of strings in Go

You can also sort a slice of strings using the sort.Strings() function:

    package main

    import (
        "fmt"
        "sort"
    )

    func main() {
        words := []string{"banana", "apple", "cherry", "date"}

        // Sort the slice in alphabetical order
        sort.Strings(words)

        fmt.Println(words) // Output: [apple banana cherry date]
    }

In this example, we define a slice of strings words, and then call the sort.Strings() function to sort the slice in alphabetical order. The sorted slice is then printed to the console using the fmt.Println() function.

How to sort a slice of struct in Go

You can sort a slice of structs by defining a custom sort function that compares the fields you want to sort on.

Here's an example:

    package main

    import (
        "fmt"
        "sort"
    )

    type Person struct {
        Name string
        Age  int
    }

    type ByAge []Person

    func (a ByAge) Len() int           { return len(a) }
    func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

    func main() {
        people := []Person{
            {"Alice", 25},
            {"Bob", 30},
            {"Charlie", 20},
        }

        // Sort the slice by age
        sort.Sort(ByAge(people))

        fmt.Println(people) // Output: [{Charlie 20} {Alice 25} {Bob 30}]
    }

Explainations: above example, we define a slice of Person structs, and then define a custom ByAge type that implements the sort.Interface interface. The Len(), Swap(), and Less() methods are defined to specify how to compare and sort the slice by age. We then call the sort.Sort() function with a ByAge instance of the people slice, and the slice is sorted by age.

Previous Article

Next Article