Are you sorted?

Tutorials

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