Go - sort example - ascending and descending orders

Sorting is arranging elements in an ordered sequence. Go’s sort package implements sorting for builtins and user-defined types.

Go sort integers

The sort.Ints sort a slice of ints in ascending order. The Reverse function returns the reverse order for data.

The example sorts a slice of integers in ascending and descending order:


package main

import (
    "fmt"
    "sort"
)

func main() {

    vals := []int{30, 10, 0, 70, 20, 40, 80, 60}
    sort.Ints(vals)
    fmt.Println(vals)

    sort.Sort(sort.Reverse(sort.IntSlice(vals)))
    fmt.Println(vals)
}

Output:

[0 10 20 30 40 60 70 80]
[80 70 60 40 30 20 10 0]

Go sort strings

The sort.Strings sort a slice of strings in ascending order.

Let's sort the days in ascending and descending orders:


package main

import (
    "fmt"
    "sort"
)

func main() {

    days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

    sort.Strings(days)
    fmt.Println(days)

    sort.Sort(sort.Reverse(sort.StringSlice(days)))
    fmt.Println(days)
}

Output:

[0 10 20 30 40 60 70 80]
[80 70 60 40 30 20 10 0]

Comments