Introducing sorting algorithms in Go

Sorting Arbitrary Data

Spoiled script kiddies will be rubbing their eyes in amazement: Go's strict type system requires quite a bit of extra overhead before it will sort an array of arbitrary data. It turns out to be impossible to define a sort routine that sorts arrays with elements of a generic data type. Instead, the programmer has to explicitly specify how Go should compare and swap the elements.

Listing 7 defines a fictitious data structure Record, which only contains an integer value as an attribute. To sort an array with elements of Record types, the programmer has to teach Go:

  • How to determine the length of the array with the data types
  • How to compare two elements at the positions i and j
  • How to swap two different entries against each other (i.e., everything a generic sort function does with its data internally while it's performing the sort)

Listing 7


01 package main
03 import (
04   "fmt"
05   "sort"
06 )
08 type Record struct {
09   id int
10 }
12 type Records []Record
14 func (r Records)
15  Len() int {
16   return len(r)
17 }
19 func (r Records) Swap(i, j int) {
20   r[i], r[j] = r[j], r[i]
21 }
23 func (r Records) Less(i, j int) bool {
24   return r[i].id < r[j].id
25 }
27 func main() {
28   data := Records{{5}, {1}, {2}, {7}, {3}}
29   sort.Sort(data)
30   fmt.Printf("%+v\n", data)
31 }

For this purpose, Listing 7 contains the Len(), Swap(), and Less() functions, to each of which you need to assign a receiver as an array of Record types (i.e., an array of the Records type defined above). You can easily determine the length of the array with the built-in Go len() function, so Len() is taken care of. Two elements are swapped courtesy of Go's practical swapping syntax (a,b = b,a), so Swap turns out to be easy-peasy. Two elements are compared using the less-than operator (<), as shown in line 24, which is the meat of Less(). To have Go sort the array in place with quicksort, line 29 calls the sort.Sort() function and passes the array with the record elements to it. The correct result, as determined by the algorithm, is shown in Listing 8.

Listing 8


$ ./sortstruct
[{id:1} {id:2} {id:3} {id:5} {id:7}]

It turns out that a language like Go with strict type checking requires a little more programming overhead than a scripting language that sorts strings, integers, and floats without complaining, or to which you could easily add a homemade sorting function for types you define yourself. This disadvantage is not only made up for by Go's high processing speed, but also by the fact that the compiler complains about accidental type errors – rather than just the program at run time. But, as usual, there's no free lunch.


  1. Knuth, Donald E. The Art of Computer Programming, Volume 3: Searching and Sorting, Addison-Wesley Professional, 1998
  2. Cormen, Thomas H., Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, MIT Press, 2009
  3. Listings for this article:
  4. Counting sort:
  5. Sort functions in the Go standard library:

The Author

Mike Schilli works as a software engineer in the San Francisco Bay area, California. Each month in his column, which has been running since 1997, he researches practical applications of various programming languages. If you email him at he will gladly answer any questions.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Exploring Quicksort

    If you wanted to assign a flavor to the Quicksort algorithm, it would be sweet and sour. Sweet, because it is very elegant; sour, because typical implementations sometimes leave more questions than they answer.

  • Tutorials – Bash Arrays

    Discover the data structures that make your shell scripts really powerful.

  • Housecleaning

    This month, Mike Schilli writes a quick terminal UI in Go to help track down space hogs on his hard disk.

  • Safe Passage

    How does a ferryman transport a wolf, a goat, and a cabbage across a river in a boat that can only carry the ferryman plus one item at a time, without the wolf eating the goat or the goat eating the cabbage while left together back on shore? Mike programs the solution in Go.

  • Top Coder

    Springtime is application time! Mike Schilli, who has experience with job application procedures at companies in Silicon Valley, digs up a question asked at the Google Engineering interview and explains a possible solution in Go.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More