Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sort
go
golang
string
int

What is the sort function in Golang?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 main
import (
"fmt"
"sort"
)
func main() {
intarray := []int{109, 58, 2, 51, 4, 97} // unsorted
fmt.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 main
import (
"fmt"
"sort"
)
func main() {
strarray := []string{"the", "quick", "brown", "fox"} // unsorted
fmt.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 main
import (
"fmt"
"sort"
)
func main() {
floatarray := []float64{109.32, 109.21, 2.93, 49.23, 4.32, 49.11} // unsorted
fmt.Println("Before sorting:",floatarray)
sort.Float64s(floatarray)
fmt.Println("After sorting:",floatarray)
}

RELATED TAGS

sort
go
golang
string
int
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring