Start learning free

LESSON 266 OF 671 · SORTING & BUILT-INS

Custom Sorting in Go

Lesson

TL ; DR:

To sort by your own rule, give sort.Slice a function. It gets two indexes, i and j. It returns true when item i goes first.


nums := []int{25, 13, 5, 41, 33}

sort.Slice(nums,
    func(i, j int) bool {
        if nums[i]%10 != nums[j]%10 {
            return nums[i]%10 < nums[j]%10
        }
        return nums[i] < nums[j]
    })
// [41 13 33 5 25]

scores := []int{70, 95, 82}

sort.Slice(scores, func(i, j int) bool { return scores[i] > scores[j] })
// [95 82 70]


Full lesson:

You met sort.Strings in the Shopping Cart project. It sorts a slice from A to Z. Sometimes you need another order. The shortest word may have to come first, or the highest score.

The sort.Slice function sorts by your own rule. Its second value is a function, written right where you need it. This function has no name. It starts with func, then come its parameters, its result type and its body.

The function gets two indexes, i and j. It returns true when the item at i must go before the item at j. The sort.Slice function calls it again and again, on two items at a time.

Watch out. The function gets indexes, not the items. Read the items with words[i] and words[j].

  • High to low: return scores[i] > scores[j].
  • Shortest first: return len(words[i]) < len(words[j]).

For two rules, check the first rule. Use the second one only on a tie, as the if above does.

Above, the first rule compares the last digits, nums[i] % 10 and nums[j] % 10. Numbers with the same last digit then go from small to large.

Comparing two strings with < puts them from A to Z.

The sort.Slice function doesn't keep equal items in their old order. Add a second rule when ties matter.

It also changes the slice itself. To keep the original, sort a copy made with slices.Clone(words).


Your task

A pet shop sells toys. Their prices are in prices. Sort prices from high to low.

The shop's pets are in names. Sort names by their last letter, in alphabetical order. Names with the same last letter go from A to Z.

The code already prints both, one item per line.

Expected output:

30
12
8
5
Bella
Luna
Bo
Coco
Max
Rex
STEP 1 OF 4
    Ctrl + Enter to check