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

Tutorial Básico Golang

Comandos de Controle Golang

Funções & Métodos Golang

Estruturas Golang

Fatias & Arrays Golang

Strings (String) Golang

Ponteiros Golang

Interfaces Golang

Concorrência Golang

Exceções Golang

Miscelâneos Golang

Ordenação do Linguagem Go (Sort)

O Go possui o pacote Sort, que pode ser usado para ordenar tipos de dados internos e definidos pelo usuário.

O pacote sort possui diferentes métodos para ordenar diferentes tipos de dados, como Ints(), Float64s(), Strings() e outros.

Podemos usar o método AreSorted() (por exemplo, Float64sAreSorted(), IntsAreSorted() e outros para verificar se os valores estão ordenados.

Exemplo de ordenação Go

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

Saída:

Ints: [5 8 10 20]
floatValue: [5.5 8.5 10.5 20.5]
Strings: [Mohan Raj Roy]
Sorted: true

Supondo que queiramos ordenar um array de strings com base no comprimento das strings, podemos implementar nosso próprio padrão de ordenação. Para isso, devemos implementar os métodos Less, Len e Swap definidos na interface de ordenação.

Então, devemos converter o array para o tipo implementado.

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

Saída:

[Washington New York London Delhi]