Sorting Data in Go: An Overview of Different Types of Sorting in Go
Gayathri R
Posted on March 6, 2023
Are you looking to sort data in your Go applications? In this blog post, we will explore the various types of sorting available in Go and how to implement them in your code. So, let's get started!
There are two main sorting options available in Go: sort.Sort and sort.Slice.
- sort.Sort:
sort.Sort is a generic sorting function that can be used to sort any type of data. It takes a slice of any type, and a comparison function as parameters. The comparison function takes two elements of the slice and returns whether the first element should come before or after the second element.
Example:
package main
import (
"fmt"
"sort"
)
func main() {
// Create a slice of integers.
data := []int{2, 4, 1, 3, 5}
// Sort the slice in ascending order.
sort.Sort(sort.IntSlice(data))
fmt.Println(data)
}
// Output:
// [1, 2, 3, 4, 5]
- sort.Slice:
sort.Slice is a convenience function that calls sort.Sort with a predefined comparison function for the type of data it is sorting. It takes a slice of any type, and an optional comparison function as parameters. If you don't provide a comparison function, it will use the default comparison function for the type.
Example:
package main
import (
"fmt"
"sort"
)
func main() {
// Create a slice of strings.
data := []string{"Bob", "Alice", "Eve"}
// Sort the slice in alphabetical order.
sort.Slice(data, func(i, j int) bool {
return data[i] < data[j]
})
fmt.Println(data)
}
// Output:
// [Alice, Bob, Eve]
Example Program for sorting a Json Array:-
package main
import (
"encoding/json"
"fmt"
"sort"
)
// Person is a struct representing a person.
type Person struct {
Name string
Age int
}
func main() {
// Create a slice of Person structs.
data := []Person{
{Name: "Alice", Age: 25},
{Name: "Bob", Age: 24},
{Name: "Charlie", Age: 50},
}
// Sort the slice in descending order by age.
sort.Slice(data, func(I, j int) bool {
return data[I].Age > data[j].Age
})
// Marshal the slice into a JSON array.
bytes, _ := json.Marshal(data)
fmt.Println(string(bytes))
}
// Output:
// [{"Name":"Charlie","Age":50},{"Name":"Alice","Age":25},{"Name":"Bob","Age":24}]
Sorting data is an essential part of many applications. In this blog post, we discussed the various types of sorting available in Go and how to implement them.
Posted on March 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.