๐ŸŽ“ A1Learner
๐Ÿ”

Go Sorting

Sorting puts the items of a slice in order. The sort changes the slice itself.

Sort numbers

Sort puts the numbers from smallest to largest. The slice itself holds the new order.

package main

import "fmt"
import "slices"

func main() {
	nums := []int{9, 2, 5, 1}
	slices.Sort(nums)
	fmt.Println(nums)
}

Sort strings

Sort puts the names in letter order. Ana comes first and Hana comes last.

package main

import "fmt"
import "slices"

func main() {
	names := []string{"Bo", "Ana", "Hana"}
	slices.Sort(names)
	fmt.Println(names)
}

Test the order

IsSorted reports false before the sort runs. It reports true after the sort runs.

package main

import "fmt"
import "slices"

func main() {
	nums := []int{3, 1, 2}
	fmt.Println(slices.IsSorted(nums))
	slices.Sort(nums)
	fmt.Println(slices.IsSorted(nums))
}

Sort in reverse

Sort puts the numbers in rising order first. Reverse then flips the slice into falling order.

package main

import "fmt"
import "slices"

func main() {
	nums := []int{3, 8, 1}
	slices.Sort(nums)
	slices.Reverse(nums)
	fmt.Println(nums)
}

Example

package main

import "fmt"
import "slices"

func main() {
	scores := []int{72, 95, 88}
	slices.Sort(scores)
	slices.Reverse(scores)
	fmt.Println(scores)
	fmt.Println("First place:", scores[0])
}

Key points

  • Use slices.Sort to put a slice in order.
  • Sort puts numbers from smallest to largest.
  • Sort puts strings in letter order.
  • Use slices.IsSorted to test whether a slice is in order.
  • Use slices.Reverse to flip the order of a slice.

In this example, scores holds three results. Sort puts the scores in rising order. Reverse flips the slice so the largest score comes first. The first item is the winning score, and the last print line shows it as 95.

Note

Sort changes the slice itself and returns nothing.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does slices.Sort do to a slice?