← 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.
Syntax
go
sort.Ints(slice)
sort.Strings(slice)
sort.Slice(slice, func(i, j int) bool {
    return slice[i] < slice[j]
})

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
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"sort"
)

// main is where the program starts running
func main() {
	// Short declaration: create nums and infer the type
	nums := []int{5, 2, 8, 1, 9}
	sort.Ints(nums)
	// Print the values followed by a newline
	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
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"sort"
)

// Define a struct type named Person
type Person struct {
	Name string
	Age  int
}

// main is where the program starts running
func main() {
	// Short declaration: create people and infer the type
	people := []Person{{"Zara", 25}, {"Amit", 30}, {"Bala", 22}}
	sort.Slice(people, func(i, j int) bool {
		// Send people[i].Age < people[j].Age back to the caller
		return people[i].Age < people[j].Age
	})
	// Print the values followed by a newline
	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
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"fmt"
	"sort"
)

// main is where the program starts running
func main() {
	// Short declaration: create nums and infer the type
	nums := []int{1, 3, 5, 7}
	// Print the values followed by a newline
	fmt.Println("already sorted:", sort.IntsAreSorted(nums))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.