Go’s |
|
package main
|
|
import "fmt"
import "sort"
|
|
func main() {
|
|
Sort methods are specific to the builtin type; here’s an example for strings. Note that sorting is in-place, so it changes the given slice and doesn’t return a new one. |
strs := []string{"c", "a", "b"}
sort.Strings(strs)
fmt.Println("Strings:", strs)
|
An example of sorting |
ints := []int{7, 2, 4}
sort.Ints(ints)
fmt.Println("Ints: ", ints)
|
We can also use |
s := sort.IntsAreSorted(ints)
fmt.Println("Sorted: ", s)
}
|
Running our program prints the sorted string and int
slices and |
$ go run sorting.go
Strings: [a b c]
Ints: [2 4 7]
Sorted: true
|
Next example: Sorting by Functions.