Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. sort Package

sort Package

Go's sort package lets you sort slices and arbitrary collections. Dedicated functions are available for integers, strings, and floating-point numbers; use sort.Slice() for any other type.

Syntax

import "sort"

// Sort int, string, and float64 slices in ascending order.
sort.Ints([]int{3, 1, 2})
sort.Strings([]string{"banana", "apple", "cherry"})
sort.Float64s([]float64{3.14, 1.41, 2.71})

// Sort any slice using a custom comparison rule.
sort.Slice(s, func(i, j int) bool {
    return s[i] < s[j]  // Elements are ordered when this returns true.
})

// Binary search in a sorted slice.
idx := sort.SearchInts(nums, 5)

// Check whether a slice is already sorted.
ok := sort.IntsAreSorted(nums)

Function list

FunctionDescription
sort.Ints(a)Sorts an int slice in ascending order (in-place).
sort.Strings(a)Sorts a string slice in ascending order (in-place).
sort.Float64s(a)Sorts a float64 slice in ascending order (in-place).
sort.Slice(s, less)Sorts any slice using the result of the less function.
sort.SliceStable(s, less)Same as sort.Slice, but preserves the original order of equal elements.
sort.Search(n, f)Returns the smallest index satisfying condition f using binary search.
sort.SearchInts(a, x)Returns the insertion position of x in a sorted int slice.
sort.SearchStrings(a, x)Returns the insertion position of x in a sorted string slice.
sort.IntsAreSorted(a)Reports whether an int slice is sorted in ascending order.
sort.StringsAreSorted(a)Reports whether a string slice is sorted in ascending order.
sort.Reverse(data)Wraps an Interface to produce descending order.

Sample code

package main

import (
    "fmt"
    "sort"
)

// Person is used to demonstrate sorting a slice of structs.
type Person struct {
    Name string
    Age  int
}

func main() {
    // Sort an integer slice.
    nums := []int{5, 2, 8, 1, 9, 3}
    fmt.Println("Before sort:", nums)
    sort.Ints(nums)
    fmt.Println("After sort (ascending):", nums)

    // Sort in reverse (descending) order.
    sort.Sort(sort.Reverse(sort.IntSlice(nums)))
    fmt.Println("After sort (descending):", nums)

    fmt.Println()

    // Sort a string slice.
    words := []string{"banana", "apple", "cherry", "date"}
    fmt.Println("Before string sort:", words)
    sort.Strings(words)
    fmt.Println("After string sort:", words)

    fmt.Println()

    // Sort a slice of structs using a custom rule.
    people := []Person{
        {"Alice", 30},
        {"Bob", 25},
        {"Carol", 35},
        {"Dave", 25},
    }
    fmt.Println("--- Sort structs by age (ascending) ---")
    sort.Slice(people, func(i, j int) bool {
        return people[i].Age < people[j].Age  // Order by age, smallest first.
    })
    for _, p := range people {
        fmt.Printf("  %s: %d\n", p.Name, p.Age)
    }

    // Stable sort: preserve the original order of people with the same age.
    fmt.Println("--- Stable sort (ascending by age, original order preserved for ties) ---")
    people2 := []Person{
        {"Alice", 30}, {"Bob", 25}, {"Carol", 35}, {"Dave", 25},
    }
    sort.SliceStable(people2, func(i, j int) bool {
        return people2[i].Age < people2[j].Age
    })
    for _, p := range people2 {
        fmt.Printf("  %s: %d\n", p.Name, p.Age)
    }

    fmt.Println()

    // Binary search in a sorted slice.
    sorted := []int{1, 3, 5, 7, 9, 11}
    idx := sort.SearchInts(sorted, 7)
    fmt.Printf("Index of 7: %d (value: %d)\n", idx, sorted[idx])
    fmt.Println("IntsAreSorted:", sort.IntsAreSorted(sorted))
}

Notes

sort.Slice() is the most versatile sorting function and accepts a custom comparison function for any type. The comparison function should return true if the element at index i should come before the element at index j.

Since Go 1.21, the slices package introduces slices.Sort(), which provides a more concise syntax using generics. Consider using the slices package in new code.

sort.Slice() is an unstable sort. Use sort.SliceStable() if you need to preserve the relative order of equal elements.

If you find any errors or copyright issues, please .