Sorting with slices
Sorting turns many hard questions into easy ones. Once a list is in order, the smallest and largest are at the ends, the middle is the median, duplicates sit next to each other, and you can search it quickly (next lesson).
slices.Sort
For a slice of numbers or strings, one call is enough:
xs := []int{42, 7, 19}
slices.Sort(xs) // [7 19 42]
words := []string{"pear", "fig", "apple"}
slices.Sort(words) // [apple fig pear]
slices.Sort sorts in place: it changes the slice you pass in. If the caller still needs the original order, sort a copy made with slices.Clone. Strings are compared byte by byte, so "Zebra" comes before "apple" (upper-case letters come first in ASCII).
slices.SortFunc and a compare function
For anything else, such as structs or a different order, give slices.SortFunc a function that compares two values a and b. It returns a negative number when a should come first, a positive number when b should come first, and 0 when they're equal. cmp.Compare from the cmp package returns exactly that:
slices.SortFunc(entries, func(a, b Entry) int {
return cmp.Compare(a.Minutes, b.Minutes) // fewest minutes first
})
Swap the arguments to sort the other way round: cmp.Compare(b.Points, a.Points) puts the most points first. For strings there's also strings.Compare.
Breaking ties
Puzzles and rankings often sort by several keys: by points, and for equal points by time, and for equal time by name. Compare the first key; only when it's a tie, move on to the next:
func(a, b Entry) int {
if c := cmp.Compare(b.Points, a.Points); c != 0 {
return c
}
return strings.Compare(a.Name, b.Name)
}
Since Go 1.22, cmp.Or can write this chain in one line. Nibble's Go runtime can't run cmp.Or yet, so in this course use if as above; on your own computer either works.
Task
This lesson's input holds the results of a kite contest: name, points and minutes on each line.
- Complete
rank(entries []Entry) []Entry: the entries sorted by most points first, then fewer minutes, then name from A to Z. Don't change theentriesargument. - Complete
medianMinutes(entries []Entry) int: the middle value of all the minutes once they're sorted. With an even number of entries, take the lower of the two middle values; with none, return0.