ProgramGuru

The sort Package

Start with The sort Package

The sort package orders slices and provides comparison tools for custom sort rules.

What you’ll learn

  • Explain the main purpose of the sort package.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

sort.Ints sorts an integer slice in ascending order in place. sort.Strings sorts strings lexicographically, and sort.Slice sorts using a comparison callback. The modern slices package offers generic alternatives.

In-place sorting changes the original slice’s elements, which also affects views sharing the same backing array. When callers require original order, copy the slice first.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for sortSearching by order depends on the data being sorted first.Unsorted sliceStep 1sort.IntsStep 2Sorted in placeStep 3Binary searchStep 4Searching by order depends on the data being sorted first.
Searching by order depends on the data being sorted first.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"sort"
)

func main() {
	scores := []int{9, 2, 7, 1}
	sort.Ints(scores)
	fmt.Println("Ascending:", scores)
	fmt.Println("Found 7:", sort.SearchInts(scores, 7))
}

Output

Ascending: [1 2 7 9]
Found 7: 2

Trace what the program does

Ints rearranges scores to [1 2 7 9]. SearchInts performs binary search on the sorted slice and returns the position 2 for the value 7.

Avoid common mistakes

  • SearchInts expects sorted data; use it only with the appropriate order.
  • sort.Ints modifies the input slice rather than creating a fresh copy.

Try it yourself

Sort a slice of names, then use sort.SearchStrings to find a chosen name.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What happens to scores after sort.Ints(scores)?
Choose one answer. You can try again.

Answer and explanation

Its elements are rearranged in place

Correct. Ints rearranges scores to [1 2 7 9].

What you should remember

You have practiced The sort Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The slices Package →