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
andj
- 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
sortstruct.go
01 package main 02 03 import ( 04 "fmt" 05 "sort" 06 ) 07 08 type Record struct { 09 id int 10 } 11 12 type Records []Record 13 14 func (r Records) 15 Len() int { 16 return len(r) 17 } 18 19 func (r Records) Swap(i, j int) { 20 r[i], r[j] = r[j], r[i] 21 } 22 23 func (r Records) Less(i, j int) bool { 24 return r[i].id < r[j].id 25 } 26 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
Results
$ ./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.
Infos
- Knuth, Donald E. The Art of Computer Programming, Volume 3: Searching and Sorting, Addison-Wesley Professional, 1998
- Cormen, Thomas H., Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, MIT Press, 2009
- Listings for this article: ftp://ftp.linux-magazine.com/pub/listings/linux-magazine.com/233/
- Counting sort: https://en.wikipedia.org/wiki/Counting_sort
- Sort functions in the Go standard library: https://golang.org/src/sort/sort.go
« Previous 1 2 3
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
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](https://www.linux-magazine.com/var/linux_magazin/storage/images/media/linux-magazine-eng-us/images/misc/learn-more/834592-1-eng-US/Learn-More_medium.png)
News
-
NVIDIA Released Driver for Upcoming NVIDIA 560 GPU for Linux
Not only has NVIDIA released the driver for its upcoming CPU series, it's the first release that defaults to using open-source GPU kernel modules.
-
OpenMandriva Lx 24.07 Released
If you’re into rolling release Linux distributions, OpenMandriva ROME has a new snapshot with a new kernel.
-
Kernel 6.10 Available for General Usage
Linus Torvalds has released the 6.10 kernel and it includes significant performance increases for Intel Core hybrid systems and more.
-
TUXEDO Computers Releases InfinityBook Pro 14 Gen9 Laptop
Sporting either AMD or Intel CPUs, the TUXEDO InfinityBook Pro 14 is an extremely compact, lightweight, sturdy powerhouse.
-
Google Extends Support for Linux Kernels Used for Android
Because the LTS Linux kernel releases are so important to Android, Google has decided to extend the support period beyond that offered by the kernel development team.
-
Linux Mint 22 Stable Delayed
If you're anxious about getting your hands on the stable release of Linux Mint 22, it looks as if you're going to have to wait a bit longer.
-
Nitrux 3.5.1 Available for Install
The latest version of the immutable, systemd-free distribution includes an updated kernel and NVIDIA driver.
-
Debian 12.6 Released with Plenty of Bug Fixes and Updates
The sixth update to Debian "Bookworm" is all about security mitigations and making adjustments for some "serious problems."
-
Canonical Offers 12-Year LTS for Open Source Docker Images
Canonical is expanding its LTS offering to reach beyond the DEB packages with a new distro-less Docker image.
-
Plasma Desktop 6.1 Released with Several Enhancements
If you're a fan of Plasma Desktop, you should be excited about this new point release.