English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Go a un paquet Sort, utilisable pour trier des types de données intégrés ainsi que personnalisés.
Le paquet sort a différentes méthodes pour trier différents types de données, telles que Ints(), Float64s(), Strings() et autres.
Nous pouvons utiliser la méthode AreSorted() (par exemple Float64sAreSorted(), IntsAreSorted() et autres pour vérifier si les valeurs sont triées.
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
输出:
Ints: [5 8 10 20] floatValue: [5.5 8.5 10.5 20.5] Strings: [Mohan Raj Roy] Sorted: true
Supposons que nous voulions trier un tableau de chaînes de caractères en fonction de leur longueur, nous pourrions également implémenter notre propre modèle de tri. À cette fin, nous devons définir nos propres méthodes Less, Len et Swap définies dans l'interface de tri.
Ensuite, nous devons convertir le tableau en le type implémenté.
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) }
输出:
[Washington New York London Delhi]