TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Sort Slice: Len, Less, Swap in Interface

Use the sort package and sort elements. Invoke the Strings and Sort methods.
Sort. As time passes, natural forces move the rock and dirt. Wind and snow cause the topmost parts of the rock to erode. Nature performs sorting.
To sort in Go we use the "sort" package. We sort strings alphabetically with Strings(). For complex things, we use Sort and define an interface (with Len, Less and Swap).Interface
Strings. This method implements an ascending (low to high, alphabetical) sort of strings. So they go from A to Z. We must add the "sort" package to our import block.

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]
Sort strings by length. Here we specify how elements in a slice are sorted. We use the "type" keyword to create a type. We implement the sort.Interface on our ByLen type.

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]
Sort keys in map. A map cannot be sorted directly. But if we get a slice of the keys from a map, we can sort that slice and loop over it, accessing the map's values.map

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
StringsAreSorted. Sometimes we want to see if a slice is already sorted. With StringsAreSorted we pass in a string slice and get a bool—true if the slice is in sorted order.

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
StringsAreSorted, benchmark. Here we introduce a method called EnsureSorted. This method sorts the string slice if StringsAreSorted returns false.

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
Ints. The Ints method has a parallel effect to Strings—it sorts Ints from low to high in numeric order. We must pass Ints() an int slice.
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]
IntsAreSorted. This method returns a bool and tells us whether an int slice is sorted. An empty slice is considered sorted (it is not unsorted).

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
Go documentation, notes. The sort package has many methods—not all are covered in this page. The Go documentation is a good resource.

Quote: Package sort provides primitives for sorting slices and user-defined collections.

Sort: golang.org
Important. Sorting is an important problem in computer languages. In Go we can use funcs like Strings() to sort simple collections.
With the sort Interface, and its funcs Len, Less and Swap, we can sort elements in more complex ways. Sorting in Go operates on slices.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf