Guide To Sorting In Go
Nov 16, 2022 · 5 min readIn this post, we’re going to take a look at various ways to sort a slice using the sort
package from Go’s standard library.
Ascending Sort
To sort a slice in ascending order, we can use the Ints(x)
, Float64(x)
, and Strings(x)
from the sort
package.
Examples:
- Sorting
int
- Sorting
float64
- Sorting
string
Notice that sort.Strings(x)
sort the elements in the string slice based on their Unicode value, that’s why all the capital letters come first.
That’s how you can sort in ascending order using Go. Pretty easy and convenient right?
But it’s not as straightforward when we need anything other than the ascending sort, like sorting the slices in descending order for example.
Let’s look at 2 other ways of sorting to solve this problem.
Sort With Custom Comparator Using sort.Slice
sort.Slice()
sorts a slice with the provided less function. But what is a less function?
Less reports whether the element with index i must sort before the element with index j.
The function signature look like this:
Now, back to our example. We can sort the slice in decreasing order this way:
At this point, you should be able to guess how the less function in sort.Ints
is implemented. Check it out!
If you actually visit the link, you’ll notice a pattern in the built-in sorting functions.
That’s because they’re implementing the sort.Interface
interface. Yes, the interface is called Interface
.
And that brings us to the final section, sorting using sort.Sort()
.
Sorting sort.Interface Using sort.Sort()
This option allow the most customization and is actually the basis of how all the sorting function is the sort
package work.
For example, sort.Ints
is actually:
You can also check the source code.
Now, let’s try to understand what the sort.Sort()
function does.
From the docs:
sort.Sort()
sorts data in ascending order as determined by the Less
method. It makes one call to data.Len
to determine n and O(n*log(n)) calls to data.Less
and data.Swap
. The sort is not guaranteed to be stable.
data.Len
, data.Less
, data.Swap
come from the sort.Interface
interface, which look like this:
By implementing sort.Interface
, we can also call sort.Sort()
on our collection.
For example, let’s create a custom struct that implement the interface:
Then we can use our custom struct like this:
Everytime you call sort.Sort
on myPets
, myPets
will be sorted using the Less
method as the comparator.
Finally, let’s go back to our example about sorting int slice in decrementing order. We can also implement a custom type for that.
And use it like this:
Of course, we don’t always have to declare our variable with our custom type. We can also use type casting for the situation when the data is already there.
Anytime we need to sort an int slice in decreasing order, we can simply type cast it to our custom type.
Wrap Up
That’s it for this post. I hope it serves you well as a quick guide to the sort
package.