Sorting in Go

James Perkins

Posted on March 20, 2020


Go sort package implements sorting for builtins and user-defined types. It’s flexibility makes sorting a breeze!

Sorting a slice full of Strings

Sorting a slice full of Strings as simple as using a simple one line sort.Strings(sliceOfStrings). Below is an example of sorting a few Strings

package main import ( "fmt" "sort" ) func main(){ strs := []string{"cheese", "apples", "bananas", "apple","carrots"} sort.Strings(strs) fmt.Println("Strings:", strs) } // This prints: //Strings: [apple apples bananas carrots cheese]

Sorting a slice full of ints

Sorting ints are just as quick a simple one line of sort.Ints(sliceofints) will sort all of your integers from smallest to largest.

package main import ( "fmt" "sort" ) func main() { ints := []int{5, 1, 4, 85, 68, 49} sort.Ints(ints) fmt.Println("Ints: ", ints) } // Prints Ints: [1 4 5 49 68 85]

Check to see if your slice is already sorted.

Go has a built in function that will return true or false based upon if a slice is sorted. Adding to the Integer code above, we can tell if the slice is sorted.

package main import ( "fmt" "sort" ) func main() { ints := []int{5, 1, 4, 85, 68, 49} s := sort.IntsAreSorted(ints) fmt.Println(s) sort.Ints(ints) fmt.Println("Ints: ", ints) n := sort.IntsAreSorted(ints) fmt.Println(n) } // Prints: // false // Ints: [1 4 5 49 68 85] // true

That was a quick article of sorting using Go! If you want to learn about looping in Go check out the previous article Looping in Go


More Posts

Cover Image for Udacity React Nanodegree review - Part 1

Udacity React Nanodegree review - Part 1

I finished the first part of the nanodegree a few days ago and decided to give an indepth review of what is covered, what you learn and what is completed by the end of it.

Cover Image for Why you don't need to be a mathematics genius to be a developer.

Why you don't need to be a mathematics genius to be a developer.

When you first start thinking about becoming a developer, one of the things you might hear is you need to be a math(s) wizz. I am here to tell you that a small number of developers need the mathematics outside of algebra.