English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在Go语言中,切片比数组更强大,灵活,方便,并且是轻量级的数据结构。切片是可变长度的序列,用于存储相似类型的元素,不允许在同一切片中存储不同类型的元素。
Go语言使您可以根据切片的类型对切片的元素进行排序。因此,使用以下函数对int类型切片进行排序。这些函数在sort包下定义,因此,您必须在程序中导入sort包才能访问这些函数:
1.整数:此函数仅用于对整数切片进行排序,并按升序对切片中的元素进行排序。
Sintassi:
func Ints(slc []int)
在这里,slc表示一个整数。让我们借助示例来讨论这个概念:
//对整数进行排序 package main import ( "fmt" "sort" ) //Main function func main() { //使用简写声明,创建和初始化切片 scl1 := []int{400, 600, 100, 300, 500, 200, 900} scl2 := []int{-23, 567, -34, 67, 0, 12, -5} //Mostra i tagli fmt.Println("Slices(Before):") fmt.Println("Slice 1: ", scl1) fmt.Println("Slice 2: ", scl2) //对整数切片进行排序 //使用Ints函数 sort.Ints(scl1) sort.Ints(scl2) //Mostra il risultato fmt.Println("\nSlices(After):") fmt.Println("Slice 1: ", scl1) fmt.Println("Slice 2: ", scl2) }
Output:
Tagli(Prima): Taglio 1: [400 600 100 300 500 200 900] Taglio 2: [-23 567 -34 67 0 12 -5] Tagli(Dopo): Taglio 1: [100 200 300 400 500 600 900] Taglio 2: [-34 -23 -5 0 12 67 567]
2. IntsAreSorted:Questa funzione viene utilizzata per verificare se il taglio int dato è in ordine (ordinato in modo crescente). Se il taglio è in ordine, questo metodo restituisce true; altrimenti, se il taglio non è in ordine, restituisce false.
Sintassi:
func IntsAreSorted(scl []int) bool
Qui,sclRappresentaParte di ints. Discutiamo questo concetto con un esempio:
//Spiegazione del programma Go su come verificare //Il dato int del taglio è stato ordinato package main import ( "fmt" "sort" ) func main() { //Creazione ed inizializzazione dei tagli //Dichiarazione abbreviata scl1 := []int{100, 200, 300, 400, 500, 600, 700} scl2 := []int{-23, 567, -34, 67, 0, 12, -5} //Mostra i tagli fmt.Println("Tagli:") fmt.Println("Taglio 1: ", scl1) fmt.Println("Taglio 2: ", scl2) //Verifica se il taglio è in ordine //Utilizzo della funzione IntsAreSorted res1 := sort.IntsAreSorted(scl1) res2 := sort.IntsAreSorted(scl2) //Mostra il risultato fmt.Println("\nRisultato:") fmt.Println("È stato ordinato il taglio 1?: ", res1) fmt.Println("È stato ordinato il taglio 2?: ", res2) }
Output:
Tagli: Taglio 1: [100 200 300 400 500 600 700] Taglio 2: [-23 567 -34 67 0 12 -5] Risultato: È stato ordinato il taglio 1?: true È stato ordinato il taglio 2?: false