Update sorting sample to use slices.Sort instead of sort package

This commit is contained in:
Eli Bendersky
2023-08-21 12:27:51 -07:00
parent 57db236e6c
commit 655a3b6a9e
4 changed files with 25 additions and 31 deletions

View File

@@ -1,4 +1,4 @@
// Go's `sort` package implements sorting for builtins
// Go's `slices` package implements sorting for builtins
// and user-defined types. We'll look at sorting for
// builtins first.
@@ -6,26 +6,25 @@ package main
import (
"fmt"
"sort"
"slices"
)
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.
// Sorting functions are generic, and work for any
// _ordered_ built-in type. For a list of ordered
// types, see [cmp.Ordered](https://pkg.go.dev/cmp#Ordered).
strs := []string{"c", "a", "b"}
sort.Strings(strs)
slices.Sort(strs)
fmt.Println("Strings:", strs)
// An example of sorting `int`s.
ints := []int{7, 2, 4}
sort.Ints(ints)
slices.Sort(ints)
fmt.Println("Ints: ", ints)
// We can also use `sort` to check if a slice is
// already in sorted order.
s := sort.IntsAreSorted(ints)
// We can also use the `slices` package to check if
// a slice is already in sorted order.
s := slices.IsSorted(ints)
fmt.Println("Sorted: ", s)
}

View File

@@ -1,2 +1,2 @@
c39a7498686fe1d74f729fd6b21a70bf063abf14
_gY0tANzJ4l
2091224c8d8ac748883215c4dbe9611fb8afacc3
X7iJcIua02T

View File

@@ -1,5 +1,3 @@
# Running our program prints the sorted string and int
# slices and `true` as the result of our `AreSorted` test.
$ go run sorting.go
Strings: [a b c]
Ints: [2 4 7]