# 如何在Golang中对整数进行排序？

Go语言允许你根据切片的类型对切片的元素进行排序。因此, 使用以下函数对int类型切片进行排序。这些功能是在sort包下定义的, 因此, 你必须在程序中导入sort包才能访问这些功能：

1.整数：此函数仅用于对一个int切片进行排序, 并按升序对切片中的元素进行排序。

``func Ints(slc []int)``

``````//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：此函数用于检查给定的int切片是否为排序形式(升序)。如果切片为排序形式, 则此方法返回true；否则, 如果切片未为排序形式, 则返回false。

``func IntsAreSorted(scl []int) bool``

``````//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``````

• 回顶