How to Sort an Array of Int Float and String in Golang

Sunday, April 25, 2021 • One minute to read

Golangto-the-point2021golangto-the-point2021

The golang provides a sort package to sort slices of primitives types and user-defined.

Sort Ints

1intArr := []int{23, 12, 11, 90}
2// Sort in Increasing Order
3sort.Ints(intArr) // [11, 12, 23, 90]
4// Sort in Decreasing Order
5sort.Sort(sort.Reverse(sort.IntSlice(intArr))) // [90, 23, 12, 11]

Sort Float

1floatArr := []float64{23.1, 12.1, 111.1, 91.0}
2// Sort in Increasing Order
3sort.Float64s(floatArr) // [12.1 23.1 91 111.1]
4// Sort in Decreasing Order
5sort.Sort(sort.Reverse(sort.Float64Slice(floatArr))) // [111.1 91 23.1 12.1]

Not-a-number (NaN) values are ordered before other values.

1floatArr := []float64{23.1, 12.1, math.NaN(), 111.1, 91.0}
2// Sort in Increasing Order
3sort.Float64s(floatArr) // [NaN 12.1 23.1 91 111.1]
4// Sort in Decreasing Order
5sort.Sort(sort.Reverse(sort.Float64Slice(floatArr))) // [111.1 91 23.1 12.1 NaN]

Sort String

1strArr := []string{"Banana", "Apple", "Orange"}
2// Sort in Increasing Order
3sort.Strings(strArr) // [Apple Banana Orange]
4// Sort in Decreasing Order
5sort.Sort(sort.Reverse(sort.StringSlice(strArr))) // [Orange Banana Apple]

Golangto-the-point2021golangto-the-point2021

PreviousCreate a Mars Weather App

NextHow to Add RSS feed to Hugo Website