How to do a custom sort in Go
Overview
Sorting is the process of arranging data in a systematic way.
When we want to sort items according to criteria that are different from the normal — for example, if we want to sort strings according to their length rather than their alphabetical order — we can use the custom sorting method.
Packages
We use the sort and the fmt package to implement this.
fmt package
The fmt package is used to output the results to the screen, as we will see in the example below.
sort package
The sort package is used in Go to sort the slices of different data types.
The sort package comes with three interfaces, as explained in the example below.
Len()Swap()Less()
In the following example, we sort strings according to their lengths.
Example
package mainimport ("fmt""sort")type byLength []stringfunc (s byLength) Len() int {return len(s)}func (s byLength) Swap(i, j int) {s[i], s[j] = s[j], s[i]}func (s byLength) Less(i, j int) bool {return len(s[i]) < len(s[j])// getting the lenght of strings}func main() {fruits := []string{"peach", "banana", "kiwi"}sort.Sort(byLength(fruits))//calling the sortfmt.Println(fruits)// outputing results}
Interface explanation
-
The
Lessinterface: If the element with indeximust sort before the one with indexj, thenLessreports it. The items at indexiandjare regarded equal if bothLess(i, j)andLess(j, j)are false. -
The
Leninterface: The number of elements in the collection is denoted byLen. -
The
Swapinterface: This performs the swapping between the two indices.
Code explanation
From the example above:
-
In lines 3-6, we first import our packages, i.e., the
fmtandsortpackages. -
In line 8, we declare a
byLengthtype which is an alias of the builtin[]stringtype. -
In line 10-12, we create a function that returns the length of a string.
-
In line 16, we use
Lessand ourbylengthtype to write the logic to get the string with the highest length. We then execute the sorting using oursortpackage to carry out the custom sorting. -
In lines 21-22, we carry out a sort on the
fruitvariable where we implement the function we’ve previously created. -
In line 24, we output the result using the
fmtpackage.