Sort

The sort algorithm sorts an array into ascending order. Sort doesn't require new containers to be created, destroyed, or copied—the sort algorithm sorts all the elements within their container. We can do this in Go with the standard library sort. Go's standard library sort has helper functions for different data types (IntsAreSorted, Float64sAreSorted, and StringsAreSorted) for sorting their respective data types. We can implement the sorting algorithm as illustrated in the following code:

package main
import (
"fmt"
"sort"
)
func main() {
intData := []int{3, 1, 2, 5, 6, 4}
stringData := []string{"foo", "bar", "baz"}
floatData := []float64{1.5, 3.6, 2.5, 10.6}

This code instantiates simple data structures with values. After this, we sort each of these data structures using the built-in sort functions, as follows:


sort.Ints(intData)
sort.Strings(stringData)
sort.Float64s(floatData)
fmt.Println("Sorted Integers: ", intData, " Sorted Strings:
", stringData, " Sorted Floats: ", floatData)
}

As we execute this, we can see that all of our slices have been sorted in order, as shown in the following screenshot:

Integers are sorted low to high, strings are sorted alphabetically, and floats are sorted low to high. These are the default sorting methods within the sort package.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156