English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales básicos de Golang

Sentencias de control de Golang

Funciones y métodos de Golang

Estructuras de Golang

Cortes y arreglos de Golang

Cadenas (String) de Golang

Punteros de Golang

Interfaces de Golang

Concurrencia de Golang

Excepciones (Error) de Golang

Misceláneos de Golang

Clasificación del lenguaje Go

Go tiene el paquete Sort, que se puede usar para ordenar tipos de datos integrados y definidos por el usuario.

El paquete sort tiene diferentes métodos para ordenar diferentes tipos de datos, como Ints(), Float64s(), Strings() y otros.

Podemos usar el método AreSorted() (por ejemplo, Float64sAreSorted(), IntsAreSorted() y otros para verificar si los valores están ordenados.

Ejemplo de ordenamiento Go

package main
import (
	"sort"
	"fmt"
)
func main() {
	intValue := []int{10, 20, 5, 8}
	sort.Ints(intValue)
	fmt.Println("Enteros:", 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("Cadenas:", stringValue)
	str := sort.Float64sAreSorted(floatValue)
	fmt.Println("Sorted: ", s

Salida:

Enteros:5 8 10 2[0]
floatValue:5.5 8.5 10.5 20.5]
Cadenas: [Mohan Raj Roy]
Sorted: true

Supongamos que queremos ordenar un array de cadenas de caracteres según su longitud, también podemos implementar nuestro propio patrón de ordenación. Para esto, debemos implementar nuestros propios métodos Less, Len y Swap definidos en la interfaz de ordenación.

Luego, debemos convertir el array al tipo de implementación correspondiente.

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)
}

Salida:

[Washington New York London Delhi]