Sorting and searching slices

Sorting a list and searching in it are jobs that almost every program needs. You can write loops for them, but Go already has ready-made functions in the slices package. Like math in the Math Functions lesson, you import it at the top of the file before you use it:

package main

import (
	"fmt"
	"slices"
)

func main() {
	nums := []int{42, 7, 19, 3, 25}
	slices.Sort(nums)
	fmt.Println(nums)
}

Output:

[3 7 19 25 42]

slices.Sort sorts from the smallest value to the largest. It changes the slice you give it and returns nothing, so you do not write nums = ... here. Strings are sorted too, letter by letter, and every capital letter comes before every small letter:

words := []string{"pear", "Apple", "fig"}
slices.Sort(words)
fmt.Println(words)

Output:

[Apple fig pear]

Searching

slices.Contains tells you if a value is in the slice. slices.Index tells you where: it returns the index of the first matching element, or -1 when there is no match:

nums := []int{42, 7, 19, 3, 25}
fmt.Println(slices.Contains(nums, 19))
fmt.Println(slices.Index(nums, 19))
fmt.Println(slices.Index(nums, 8))

Output:

true
2
-1

Always check for -1 before you use the result as an index. Go has no element at index -1, so nums[pos] with pos equal to -1 stops the program with the panic index out of range [-1].

Largest, smallest and reversed

slices.Max and slices.Min return the largest and the smallest element. slices.Reverse turns the order around, in place like slices.Sort:

nums := []int{42, 7, 19, 3, 25}
fmt.Println(slices.Max(nums), slices.Min(nums))
slices.Reverse(nums)
fmt.Println(nums)

Output:

42 3
[25 3 19 7 42]

An empty slice has no largest element, so slices.Max stops the program on one:

var empty []int
fmt.Println(slices.Max(empty))

Output:

panic: slices.Max: empty list

Finding the largest by hand

In coding interviews, you are often asked to write this loop yourself. Start with the first element, then compare every other element with the best one so far:

nums := []int{42, 7, 19, 3, 25}
largest := nums[0]
for _, n := range nums[1:] {
	if n > largest {
		largest = n
	}
}
fmt.Println(largest)

Output:

42

Why start with nums[0] and not with 0? If every number in the slice were negative, a start value of 0 would never be replaced, and the answer would be 0, a number that is not in the slice. slices.Max does the same work as this loop. In real programs, use slices.Max. Learn the loop because it is the base of many other problems.

Your own order with sort.Slice

slices.Sort always uses the order from small to large. For any other order, use sort.Slice from the sort package. You give it the slice and a function, like the function values in the Function Values lesson. sort.Slice calls your function with two indexes, i and j, and your function returns true when the element at i should come first:

nums := []int{42, 7, 19, 3, 25}
sort.Slice(nums, func(i, j int) bool {
	return nums[i] > nums[j]
})
fmt.Println(nums)

Output:

[42 25 19 7 3]

With >, bigger numbers come first, so the slice is sorted from largest to smallest. The function can compare anything. This one sorts words by their length:

words := []string{"kiwi", "fig", "banana"}
sort.Slice(words, func(i, j int) bool {
	return len(words[i]) < len(words[j])
})
fmt.Println(words)

Output:

[fig kiwi banana]

In the exercise, sort a list of numbers with slices.Sort and use slices.Index to find where a target number is.