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

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception(Error)

Golang Miscellaneous

Go Language Sorting (Sort)

Go has the Sort package, which can be used to sort built-in as well as user-defined data types.

The sort package has different methods to sort different data types, such as Ints(), Float64s(), Strings() etc.).

We can use the AreSorted() method (e.g., Float64sAreSorted(), IntsAreSorted() etc. to check if the values are sorted.

Go Sorting Example

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

Assuming we want to sort a string array based on the length of the strings, we can also implement our own sorting pattern. To do this, we must implement our own Less, Len, and Swap methods defined in the sorting interface.

Then, we must convert the array to the type of the implementation.

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]