← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 5 of 10

The sort Package

The sort package is Go's way of putting a jumbled list back into order, whether it's numbers, words, or something entirely custom you define the order for.

Sorting Basic Slices

The sort package provides direct sorting functions for the most common slice types -- sort.Ints, sort.Strings, and sort.Float64s -- which sort the given slice in place, ascending.

Example: Sorting Basic Slices

markup
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{5, 2, 8, 1, 9}
	sort.Ints(nums)
	fmt.Println(nums)
}

Custom Sorting with sort.Slice

sort.Slice sorts any slice according to a custom comparison function you supply, which should return true when the element at index i belongs before the element at index j.

Example: Custom Sorting with sort.Slice

markup
package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	people := []Person{{"Zara", 25}, {"Amit", 30}, {"Bala", 22}}
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})
	fmt.Println(people)
}

Checking If a Slice Is Sorted

sort.IntsAreSorted (and its counterparts) check whether a slice is already in ascending order without modifying it, useful for validating assumptions before relying on binary search or similar.

Example: Checking If a Slice Is Sorted

markup
package main

import (
	"fmt"
	"sort"
)

func main() {
	nums := []int{1, 3, 5, 7}
	fmt.Println("already sorted:", sort.IntsAreSorted(nums))
}
Common Mistakes
  1. Calling sort.Sort with a slice directly instead of implementing sort.Interface, or forgetting sort.Slice's comparison function must return a strict less-than boolean.
  2. Assuming sort.Strings/Ints sort is stable -- for custom types needing stability, sort.SliceStable is required instead.
  3. Forgetting sort.Slice sorts the slice in place and returns nothing -- there's no return value to reassign.
Chapter Summary
  • sort.Ints, sort.Strings, and sort.Float64s sort slices of those basic types in place.
  • sort.Slice sorts any slice using a custom less-than comparison function.
  • sort.SliceStable preserves the relative order of equal elements, unlike plain sort.Slice.
  • sort.Search performs binary search on an already-sorted slice.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.