Home »
Golang »
Golang Reference
Golang sort.Sort() Function with Examples
Golang | sort.Sort() Function: Here, we are going to learn about the Sort() function of the sort package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 14, 2021
sort.Sort()
The Sort() function is an inbuilt function of the sort package which is used to sort the data (interface). It makes one call to data.Len to determine n and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable.
It accepts a parameter (data) and returns the sorted data.
Syntax
func Sort(data Interface)
Parameters
- data : An interface to be sorted.
Return Value
The Sort() function does not return any value.
Example 1
// Golang program to demonstrate the
// example of sort.Sort() Function
package main
import (
"fmt"
"sort"
)
type Product struct {
Name string
Qty int
Price float64
}
type SortedByPrice []Product
func (s SortedByPrice) Len() int {
return len(s)
}
func (s SortedByPrice) Less(i, j int) bool {
return s[i].Price < s[j].Price
}
func (s SortedByPrice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
prd := []Product{
{"Induction", 100, 4999.99},
{"Oven", 150, 5000.00},
{"Refrigerator", 50, 15900.00},
{"Toaster", 200, 999.00},
}
fmt.Println("Before sorting...")
fmt.Println(prd)
// Sorting by Name
sort.Sort(SortedByPrice(prd))
fmt.Println("After sorting...")
fmt.Println(prd)
}
Output:
Before sorting...
[{Induction 100 4999.99} {Oven 150 5000} {Refrigerator 50 15900} {Toaster 200 999}]
After sorting...
[{Toaster 200 999} {Induction 100 4999.99} {Oven 150 5000} {Refrigerator 50 15900}]
Golang sort Package »