Skip to content

Commit

Permalink
Update sorting sample to use slices.Sort instead of sort package
Browse files Browse the repository at this point in the history
  • Loading branch information
eliben committed Aug 21, 2023
1 parent 57db236 commit 655a3b6
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 31 deletions.
21 changes: 10 additions & 11 deletions examples/sorting/sorting.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,30 @@
// 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.

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)
}
4 changes: 2 additions & 2 deletions examples/sorting/sorting.hash
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
c39a7498686fe1d74f729fd6b21a70bf063abf14
_gY0tANzJ4l
2091224c8d8ac748883215c4dbe9611fb8afacc3
X7iJcIua02T
2 changes: 0 additions & 2 deletions examples/sorting/sorting.sh
Original file line number Diff line number Diff line change
@@ -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]
Expand Down
29 changes: 13 additions & 16 deletions public/sorting

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 655a3b6

Please sign in to comment.