Sorting in Go: Built-in and Custom Approaches

1. Default Sorting

Go provides built-in sorting capabilities through the sort package. The sorting operations modify the slice in place, meaning the original slice is changed directly without creating a new one.

package main

import "fmt"
import "sort"

func main() {

    // Strings can be sorted using sort.Strings()
    colors := []string{"red", "green", "blue"}
    sort.Strings(colors)
    fmt.Println("Colors:", colors)

    // Integer slices are sorted with sort.Ints()
    numbers := []int{42, 15, 8, 23}
    sort.Ints(numbers)
    fmt.Println("Numbers:", numbers)

    // Check whether a slice is already sorted
    status := sort.IntsAreSorted(numbers)
    fmt.Println("Is sorted:", status)
}

Running this code produces the following output:

1 Colors: [blue green red]
2 Numbers: [8 15 23 42]
3 Is sorted: true

As demonstrated, different slice types require different sorting functions. The sorting functinos operate directly on the input slice and do not return the sorted result.

2. Custom Sorting

Implmeenting custom sorting in Go requires defining a type that satisfies the sort.Interface contract. This involves implementing three methods: Len() for the slice length, Less() for the actual comparison logic, and Swap() for exchanging elements. The following example shows how to sort strings by their length by creating a ByLength type.

package main

import "sort"
import "fmt"

// Create a custom type for sorting
type ByLength []string

// Implement the three required methods of sort.Interface
func (b ByLength) Len() int {
    return len(b)
}

// Swap exchanges elements at positions i and j
func (b ByLength) Swap(i, j int) {
    b[i], b[j] = b[j], b[i]
}

// Less defines the sorting logic - shorter strings come first
func (b ByLength) Less(i, j int) bool {
    return len(b[i]) < len(b[j])
}

func main() {
    fruits := []string{"apple", "fig", "banana"}
    sort.Sort(ByLength(fruits))
    fmt.Println(fruits)
}

The output shows the fruits ordered by string length:

1 [fig apple banana]

Tags: Go Golang Sorting sort-package sort-interface

Posted on Mon, 18 May 2026 00:23:15 +0000 by cytech