Sorting {.en}

排序 {.zh}

::: {.en} Go’s sort package implements sorting for builtins and user-defined types. We’ll look at sorting for builtins first. :::

::: {.zh}

Go的sort包实现了对builtins和用户定义类型的排序。我们先来看看对于建筑物的分类。

:::

  1. package main
  2. import "fmt"
  3. import "sort"
  4. func main() {

::: {.en} 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. :::

::: {.zh}

排序方法特定于内置类型;这是字符串的示例。请注意,排序是在位,因此它会更改给定的切片而不会返回新的切片。

:::

  1. strs := []string{"c", "a", "b"}
  2. sort.Strings(strs)
  3. fmt.Println("Strings:", strs)

::: {.en} An example of sorting ints. :::

::: {.zh}

排序ints的一个例子。

:::

  1. ints := []int{7, 2, 4}
  2. sort.Ints(ints)
  3. fmt.Println("Ints: ", ints)

::: {.en} We can also use sort to check if a slice is already in sorted order. :::

::: {.zh}

我们也可以使用sort来检查切片是否已按排序顺序排列。

:::

  1. s := sort.IntsAreSorted(ints)
  2. fmt.Println("Sorted: ", s)
  3. }

::: {.en} Running our program prints the sorted string and int slices and true as the result of our AreSorted test. :::

::: {.zh}

运行我们的程序打印排序的字符串和intslices以及true作为我们AreSorted测试的结果。

:::

  1. $ go run sorting.go
  2. Strings: [a b c]
  3. Ints: [2 4 7]
  4. Sorted: true