Problem Solving with Go course

Sorting and SearchingSorting with slices

Problem Solving with Go

Display

Theme

Sorting and Searching · Test exercise

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.

  1. Complete rank(entries []Entry) []Entry: the entries sorted by most points first, then fewer minutes, then name from A to Z. Don't change the entries argument.
  2. 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, return 0.
main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"slices"
	"strconv"
	"strings"
)

// Entry is one team's result in a kite contest.
type Entry struct {
	Name    string
	Points  int
	Minutes int
}

// rank returns the entries in ranking order: most points first, then fewer minutes,
// then by name from A to Z. The entries argument is not changed.
func rank(entries []Entry) []Entry {
	// TODO: sort a copy with slices.SortFunc and a compare function
	return slices.Clone(entries)
}

// medianMinutes returns the middle value of the minutes once they are sorted; with an
// even number of entries, the lower of the two middle values. It returns 0 for no entries.
func medianMinutes(entries []Entry) int {
	// TODO: collect the minutes, slices.Sort them, pick the middle
	return 0
}

func main() {
	var entries []Entry
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) != 3 {
			continue
		}
		points, err1 := strconv.Atoi(f[1])
		minutes, err2 := strconv.Atoi(f[2])
		if err1 != nil || err2 != nil {
			fmt.Println("bad line:", scanner.Text())
			return
		}
		entries = append(entries, Entry{f[0], points, minutes})
	}
	for i, e := range rank(entries) {
		fmt.Printf("%d. %-6s %3d points %3d min\n", i+1, e.Name, e.Points, e.Minutes)
	}
	fmt.Println("median minutes:", medianMinutes(entries))
}
Go runtime not loaded yet

6 lines · 66 B of the 1 MB limit. Submit always uses the lesson's own input.