liveBook · Manning

Sorting algorithm

As explained in Learn Go with Pocket-Sized Projects

Sorting is the technique of ordering elements in a collection according to a specified comparison criterion.

Sorting orders a slice according to a comparison function. Go’s sort.Slice accepts the slice and a function that decides whether one indexed item precedes another. section 3.2.3

Use sorting to make collection results predictable and testable:

  • Separate sorting logic from the algorithm that finds or transforms data. section 3.2.3
  • Remember that sort.Slice modifies the original slice rather than returning a sorted copy. section 3.2.3
  • Choose comparison criteria deliberately; string comparisons use UTF encoding, placing Greek titles after Latin titles. section 3.2.3

Books ordered by author, then title

A comparator first compares Author fields and, when they match, compares Title fields. This produces a deterministic book list and simplifies testing. section 3.2.3

Listing 3.18 bookworm.go: Sorting the books
// sortBooks sorts the books by Author and then Title.
func sortBooks(books []Book) []Book {
    sort.Slice(books, func(i, j int) bool { #1
        if books[i].Author != books[j].Author {
            return books[i].Author < books[j].Author #2
        }
        return books[i].Title < books[j].Title #2
    })

    return books
}

The complete Go implementation wraps sort.Slice in sortBooks and returns the reordered slice. section 3.2.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains custom comparators, multi-field ordering, slice mutation, and string-encoding limitations, but defers deeper sort details.
Examples
Uses books sorted by author then title and habits sorted by creation time.
What it assumes
Assumes familiarity with Go slices and functions while demonstrating anonymous functions as comparator arguments.
What you can do after
Apply it via Go’s sort.Slice to order slices deterministically with custom comparison logic.
How it connects
Connects sorting with slices, maps, anonymous functions, comparison criteria, determinism, and testing.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.