Golang 如何对一个ints的slice进行排序
在Go语言中slice比数组更强大、更灵活、更方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
Go语言允许你根据其类型对slice的元素进行排序。因此,一个int类型的片断可以通过使用以下函数进行排序。这些函数是在sort包中定义的,因此,你必须在你的程序中导入sort包来访问这些函数。
1.Ints: 这个函数只用于对一个int类型的片断进行排序,它对片断中的元素按递增的顺序进行排序。
语法
func Ints(slc []int)
在这里,slc代表一个ints的片断。让我们借助于一个例子来讨论这个概念。
例子
// Go program to illustrate how
// to sort the slice of ints
package main
import (
"fmt"
"sort"
)
// Main function
func main() {
// Creating and initializing slices
// Using shorthand declaration
scl1 := []int{400, 600, 100, 300, 500, 200, 900}
scl2 := []int{-23, 567, -34, 67, 0, 12, -5}
// Displaying slices
fmt.Println("Slices(Before):")
fmt.Println("Slice 1: ", scl1)
fmt.Println("Slice 2: ", scl2)
// Sorting the slice of ints
// Using Ints function
sort.Ints (scl1)
sort.Ints (scl2)
// Displaying the result
fmt.Println("\nSlices(After):")
fmt.Println("Slice 1 : ", scl1)
fmt.Println("Slice 2 : ",scl2)
}
输出
Slices(Before):
Slice 1: [400 600 100 300 500 200 900]
Slice 2: [-23 567 -34 67 0 12 -5]
Slices(After):
Slice 1 : [100 200 300 400 500 600 900]
Slice 2 : [-34 -23 -5 0 12 67 567]
2.IntsAreSorted: 这个函数用来检查给定的ints片断是否处于排序形式(按递增顺序)。如果该片段处于排序状态,则该方法返回true;如果该片段不处于排序状态,则返回false。
语法
func IntsAreSorted(scl []int) bool
这里,scl代表一个ints的片断。让我们借助于一个例子来讨论这个概念。
例子
// Go program to illustrate how to check
// whether the given slice of ints is in
// sorted form or not
package main
import (
"fmt"
"sort"
)
// Main function
func main() {
// Creating and initializing slices
// Using shorthand declaration
scl1 := []int{100, 200, 300, 400, 500, 600, 700}
scl2 := []int{-23, 567, -34, 67, 0, 12, -5}
// Displaying slices
fmt.Println("Slices:")
fmt.Println("Slice 1: ", scl1)
fmt.Println("Slice 2: ", scl2)
// Checking the slice is in sorted form or not
// Using IntsAreSorted function
res1 := sort.IntsAreSorted(scl1)
res2 := sort.IntsAreSorted(scl2)
// Displaying the result
fmt.Println("\nResult:")
fmt.Println("Is Slice 1 is sorted?: ", res1)
fmt.Println("Is Slice 2 is sorted?: ", res2)
}
输出
Slices:
Slice 1: [100 200 300 400 500 600 700]
Slice 2: [-23 567 -34 67 0 12 -5]
Result:
Is Slice 1 is sorted?: true
Is Slice 2 is sorted?: false
极客教程