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.
We use the sort
and the fmt
package to implement this.
fmt
packageThe fmt
package is used to output the results to the screen, as we will see in the example below.
sort
packageThe 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.
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}
The Less
interface: If the element with index i
must sort before the one with index j
, then Less
reports it. The items at index i
and j
are regarded equal if both Less(i, j)
and Less(j, j)
are false.
The Len
interface: The number of elements in the collection is denoted by Len
.
The Swap
interface: This performs the swapping between the two indices.
From the example above:
In lines 3-6, we first import our packages, i.e., the fmt
and sort
packages.
In line 8, we declare a byLength
type which is an alias of the builtin []string
type.
In line 10-12, we create a function that returns the length of a string.
In line 16, we use Less
and our bylength
type to write the logic to get the string with the highest length. We then execute the sorting using our sort
package to carry out the custom sorting.
In lines 21-22, we carry out a sort on the fruit
variable where we implement the function we’ve previously created.
In line 24, we output the result using the fmt
package.