Home » Core Golang » How to sort an array/slice in Golang

How to sort an array/slice in Golang

To sort slices of basic types, use the sort package utilities. Here is an example that sorts a slice of string, a slice of int and a slice of float.

package main

import (
	"fmt"
	"sort"
)

func main() {
	// string sort
	sl := []string{"mumbai", "london", "tokyo", "seattle"}
	sort.Strings(sl)
	fmt.Println(sl)

	// int sort
	intSlice := []int{3,5,6,4,2,293,-34}
	sort.Ints(intSlice)
	fmt.Println(intSlice)

	// float sort
	floatSlice := []float64{3.2,5.6,6.4,2.293,-34.1}
	sort.Float64s(floatSlice)
	fmt.Println(floatSlice)

	// custom sort
	family := []struct {
		Name string
		Age  int
	}{
		{"Selim", 34},
		{"Umut", 23},
		{"Keko", 2},
		{"Vincent", 25},
	}

	// Sort by age, keeping original order or equal elements.
	sort.SliceStable(family, func(i, j int) bool {
		return family[i].Age < family[j].Age
	})
	fmt.Println(family)

}

Performance and time complexity

All algorithms in the Go sort package make O(n log n) comparisons in the worst case, where n is the number of elements to be sorted.

Most of the functions are implemented using an optimized version of quick sort.

akotako

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top