English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Go ha il pacchetto Sort, che può essere utilizzato per ordinare tipi di dati nativi e definiti dall'utente.
Il pacchetto sort ha diversi metodi per ordinare diversi tipi di dati, ad esempio Ints(), Float64s(), Strings() ecc.
Possiamo utilizzare il metodo AreSorted() (ad esempio Float64sAreSorted(), IntsAreSorted() ecc.) per verificare se i valori sono ordinati.
package main import ( "sort" "fmt" ) func main() { intValue := []int{10, 20, 5, 8} sort.Ints(intValue) fmt.Println("Ints: ", intValue) floatValue := []float64{10.5, 20.5, 5.5, 8.5} sort.Float64s(floatValue) fmt.Println("floatValue: ", floatValue) stringValue := []string{"Raj", "Mohan", "Roy"} sort.Strings(stringValue) fmt.Println("Strings:", stringValue) str := sort.Float64sAreSorted(floatValue) fmt.Println("Sorted: ", s
Output:
Ints: [5 8 10 20] floatValue: [5.5 8.5 10.5 20.5] Strings: [Mohan Raj Roy] Sorted: true
Supponiamo che vogliamo ordinare un array di stringhe in base alla lunghezza, possiamo anche implementare il nostro modello di ordinamento. Per questo, dobbiamo implementare i metodi Less, Len e Swap definiti nell'interfaccia di ordinamento.
Poi, dobbiamo convertire l'array in un tipo implementato.
package main import "sort" import "fmt" type OrderByLengthDesc []string func (s OrderByLengthDesc) Len() int { return len(s) } func (str OrderByLengthDesc) Swap(i, j int) { str[i], str[j] = str[j], str[i] } func (s OrderByLengthDesc) Less(i, j int) bool { return len(s[i]) > len(s[j]) } func main() { city := []string{"New York", "London","Washington","Delhi"} sort.Sort(OrderByLengthDesc(city)) fmt.Println(city) }
Output:
[Washington New York London Delhi]