Golang has a built-in sort
function that can be used to sort slices of strings, integers, and floating-point numbers.
Sorting is done using one of these functions:
sort.Ints
sort.Float64s
sort.Strings
sort.Ints
The sort.Ints
function sorts a slice of integers in ascending order.
package mainimport ("fmt""sort")func main() {intarray := []int{109, 58, 2, 51, 4, 97} // unsortedfmt.Println("Before sorting:",intarray)sort.Ints(intarray)fmt.Println("After sorting:",intarray)}
sort.Strings
The sort.Strings
function sorts a slice of strings in ascending order.
package mainimport ("fmt""sort")func main() {strarray := []string{"the", "quick", "brown", "fox"} // unsortedfmt.Println("Before sorting:",strarray)sort.Strings(strarray)fmt.Println("After sorting:",strarray)}
sort.Float64s
The sort.Float64s
function sorts a slice of floating-point values in ascending order.
package mainimport ("fmt""sort")func main() {floatarray := []float64{109.32, 109.21, 2.93, 49.23, 4.32, 49.11} // unsortedfmt.Println("Before sorting:",floatarray)sort.Float64s(floatarray)fmt.Println("After sorting:",floatarray)}
Free Resources