Select Page

Are you sorted?

Written By James Perkins

January 18, 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

You May Also Like…

Looping in Go

Looping in Go

Looping in Go is fairly similar to any other language that you may of seen in the past, with some slight variations...

Git Command Line Basics

Git Command Line Basics

It's 2020, you have started to lean coding it's great to use an GUI like gitKraken however in some roles you might not...

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *