C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
In-place: The Strings method operates in-place. So we do not need to assign anything to it—it modifies the slice.
Slice: The Strings method, as well as other methods in "sort," all operate on slices. This is the standard Go approach.
Result: The strings are sorted alphabetically—so "bird" comes first and "zebra" last.
Golang program that uses sort, Strings method
package main
import (
"fmt"
"sort"
)
func main() {
animals := []string{"cat", "bird", "zebra", "fox"}
// Sort strings.
sort.Strings(animals)
// Print results.
fmt.Println(animals)
}
Output
[bird cat fox zebra]
Len: This method is required by sort.Interface. It is used by the sort.Sort func.
Less: This compares two elements of the type. Here we use custom code to compare the lengths of two elements.
Swap: This is used by the sorting algorithm to swap two elements in the collection.
Result: The program sorts the strings by their lengths, from shortest to longest. They are not alphabetized.
Golang program that sorts strings by length
package main
import (
"fmt"
"sort"
)
// Implement length-based sort with ByLen type.
type ByLen []string
func (a ByLen) Len() int { return len(a) }
func (a ByLen) Less(i, j int) bool { return len(a[i]) < len(a[j]) }
func (a ByLen) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func main() {
// These elements are not sorted.
elements := []string{"ruby", "python", "java", "go"}
// Sort the elements by length.
sort.Sort(ByLen(elements))
// Print results.
fmt.Println(elements)
}
Output
[go ruby java python]
Important: In this example, we are not sorting the map, but sorting a slice of the map's keys. The original map is unchanged.
Golang program that sorts keys from map
package main
import (
"fmt"
"sort"
)
func main() {
codes := map[string]int{
"xyz": 1,
"ghi": 1,
"abc": 1,
"def": 1,
}
// Get keys from map.
keys := []string{}
for key, _ := range codes {
keys = append(keys, key)
}
// Sort string keys.
sort.Strings(keys)
// Loop over sorted key-value pairs.
for i := range keys {
key := keys[i]
value := codes[key]
fmt.Printf("%v = %v", key, value)
fmt.Println()
}
}
Output
abc = 1
def = 1
ghi = 1
xyz = 1
Here: Both string slices are already sorted. An empty slice is considered sorted.
Golang program that uses StringsAreSorted
package main
import (
"fmt"
"sort"
)
func main() {
animalsSorted := []string{"bird", "cat", "dog"}
animalsEmpty := []string{}
// Test to see if the string slices are sorted.
if sort.StringsAreSorted(animalsSorted) {
fmt.Println("A")
}
if sort.StringsAreSorted(animalsEmpty) {
fmt.Println("B")
}
}
Output
A
B
Version 1: In this version of the code, we call the StringsAreSorted method before using sort.Strings.
Version 2: Here we just call sort.Strings directly, without testing if the slice needs to be sorted first.
Result: The EnsureSorted method with StringsAreSorted takes about the same amount of time assorting an already-sorted slice.
So: We cannot optimize with EnsureSorted. But if we cache the result of StringsAreSorted and avoid calling it repeatedly, this could help.
Golang program that benchmarks StringsAreSorted
package main
import (
"fmt"
"sort"
"time"
)
func EnsureSorted(elements []string) {
if !sort.StringsAreSorted(elements) {
sort.Strings(elements);
}
}
func main() {
elements := []string{"aaa", "b", "c", "ddd", "e"}
t0 := time.Now()
// Version 1: sort if StringsAreSorted returns false.
for i := 0; i < 10000000; i++ {
EnsureSorted(elements)
}
t1 := time.Now()
// Version 2: always sort.
for i := 0; i < 10000000; i++ {
sort.Strings(elements)
}
t2 := time.Now()
// Results.
fmt.Println(t1.Sub(t0))
fmt.Println(t2.Sub(t1))
}
Output
2.9944054s EnsureSorted
2.9071126s strings.Sort
Golang program that sorts ints
package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{10, 0, 20, 1}
// Sort ints in ascending order.
sort.Ints(numbers)
fmt.Println(numbers)
}
Output
[0 1 10 20]
Tip: With IntsAreSorted, we can test the result in an if-statement. If false, we could call Ints to ensure the values are sorted.
Golang program that uses IntsAreSorted
package main
import (
"fmt"
"sort"
)
func main() {
numbersUnsorted := []int{100, 1, 5}
numbersSorted := []int{1, 5, 100}
numbersEmpty := []int{}
if sort.IntsAreSorted(numbersUnsorted) {
// Not reached.
fmt.Println("A")
}
if sort.IntsAreSorted(numbersSorted) {
fmt.Println("B")
}
if sort.IntsAreSorted(numbersEmpty) {
fmt.Println("C")
}
}
Output
B
C
Quote: Package sort provides primitives for sorting slices and user-defined collections.
Sort: golang.org