0
0
GoHow-ToBeginner · 3 min read

How to Sort in Descending Order in Go: Simple Guide

In Go, to sort a slice in descending order, use the sort.Slice function with a custom comparison that reverses the usual order. This involves passing a function that returns true when the first element is greater than the second, effectively sorting from largest to smallest.
📐

Syntax

The sort.Slice function sorts a slice based on a custom comparison function you provide. The syntax is:

sort.Slice(slice, func(i, j int) bool {
return slice[i] > slice[j]
})

Here, slice is the slice you want to sort. The function compares elements at positions i and j. Returning true means the element at i should come before the element at j. Using > sorts in descending order.

go
sort.Slice(slice, func(i, j int) bool {
    return slice[i] > slice[j]
})
💻

Example

This example shows how to sort a slice of integers in descending order using sort.Slice. It prints the slice before and after sorting.

go
package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{5, 2, 9, 1, 7}
    fmt.Println("Before sorting:", numbers)

    sort.Slice(numbers, func(i, j int) bool {
        return numbers[i] > numbers[j]
    })

    fmt.Println("After sorting in descending order:", numbers)
}
Output
Before sorting: [5 2 9 1 7] After sorting in descending order: [9 7 5 2 1]
⚠️

Common Pitfalls

A common mistake is to use < in the comparison function, which sorts in ascending order instead of descending. Another pitfall is forgetting to import the sort package, which causes compilation errors.

Also, sorting a slice of structs requires accessing the correct field inside the comparison function.

go
package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{3, 8, 4}

    // Wrong: sorts ascending, not descending
    sort.Slice(numbers, func(i, j int) bool {
        return numbers[i] < numbers[j] // ascending order
    })
    fmt.Println("Wrong ascending sort:", numbers)

    // Correct: descending order
    sort.Slice(numbers, func(i, j int) bool {
        return numbers[i] > numbers[j]
    })
    fmt.Println("Correct descending sort:", numbers)
}
Output
Wrong ascending sort: [3 4 8] Correct descending sort: [8 4 3]
📊

Quick Reference

Remember these tips when sorting in descending order in Go:

  • Use sort.Slice with a comparison function returning true when slice[i] > slice[j].
  • Import the sort package.
  • For slices of structs, compare the desired field inside the function.
  • Use sort.SliceStable if you want to keep the original order of equal elements.

Key Takeaways

Use sort.Slice with a custom comparison returning true when the first element is greater to sort descending.
Always import the sort package to access sorting functions.
For complex types, compare the specific field inside the comparison function.
Using < sorts ascending; use > for descending order.
sort.SliceStable preserves the order of equal elements if needed.